search
HomeBackend DevelopmentPython TutorialPython object-oriented obtaining object information

Python object-oriented obtaining object information

Apr 14, 2018 am 10:28 AM
pythonobjectObtain

The content shared with you in this article is about obtaining object information in Python object-oriented. It has certain reference value. Friends in need can refer to it

When we get a reference to an object, How do you know what type this object is and what methods it has?

Use type()

First, we determine the object type, using the type() function:

Basic types can be judged using type():

>>> type(123)
<class &#39;int&#39;>
>>> type(&#39;jeff&#39;)
<class &#39;str&#39;>
>>> type(True)
<class &#39;bool&#39;>
>>> type(None)
<class &#39;NoneType&#39;>

If a variable points to a function or class, you can also use type() to determine:

>>> type(abs)
<class &#39;builtin_function_or_method&#39;>

But what type does the type() function return? It returns the corresponding Class type. If we want to judge in an if statement, we need to compare whether the type of the two variables is the same:

>>> type(123) == type(456)
True
>>> type(&#39;jeff&#39;) == type(&#39;1993&#39;)
True
>>> type(&#39;jeff&#39;) == str
True
>>> type(123) == int
True
>>> type(123) == type(&#39;jeff&#39;)
False

To judge the basic data type, you can directly write int, str, etc., but what if you want to judge whether an object is a function? manage? You can use the constants defined in the types module:

>>> import types
>>> def fn():
...     pass
...
>>> type(fn) == types.FunctionType
True
>>> type(abs) == types.BuiltinFunctionType
True
>>> type(lambda x:x) == types.LambdaType
True
>>> type((x for x in range(10))) == types.GeneratorType
True

Use isinstance()

For class inheritance relationships, it is very inconvenient to use type(). If we want to determine the type of class, we can use the isinstance() function.

Let’s review the last example. If the inheritance relationship is:

object, Animal, Dog, Husky

class Animal(object):
    def run(self):
        print(&#39;Animal is running...&#39;)

class Dog(Animal):
    def run(self):
        print(&#39;Dog is haha running...&#39;)

    def eat(self):
        print(&#39;Eating meat...&#39;)
class Cat(Animal):
    def run(self):
        print(&#39;Cat is miaomiao running...&#39;)

    def eat(self):
        print(&#39;Eating fish...&#39;)
class Husky(Dog):
    def run(self):
        print(&#39;Husky is miaomiao running...&#39;)
dog = Dog()
dog.run()
dog.eat()
xinxin = Husky()
xinxin.run()
cat = Cat()
cat.run()
cat.eat()
Dog is haha running...
Eating meat...
Husky is miaomiao running...
Cat is miaomiao running...
Eating fish...

Then, isinstance() can tell us whether an object is a certain type. First create 3 types of objects:

a= Animal()
d = Dog()
h = Husky()
print(isinstance(h,Husky))
print(isinstance(h,Dog))
print(isinstance(h,Animal))
print(isinstance(h,object))
print(isinstance(&#39;a&#39;,str))
print(isinstance(123,int))
True
True
True
True
True
True
print(isinstance(d,Husky))
False

and you can also determine whether a variable is one of certain types. For example, the following code can determine whether it is a list or a tuple:

>>> isinstance([1,2,3],(tuple,list))
True
>>> isinstance((1,2,3),(tuple,list))
True
>>> isinstance(1,(tuple,list))
False

Use dir()

If you want to get all the properties and methods of an object, you can use the dir() function, which returns a list containing strings, for example, getting a str object All attributes and methods:

>>> dir(123)
[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__bool__&#39;, &#39;__ceil__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__pmod__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__float__&#39;, &#39;__floor__&#39;, &#39;__floorp__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__index__&#39;, &#39;__init__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__le__&#39;, &#39;__lshift__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__or__&#39;, &#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rpmod__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloorp__&#39;, &#39;__rlshift__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__round__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;, &#39;__rsub__&#39;, &#39;__rtruep__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truep__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;, &#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;from_bytes&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;, &#39;to_bytes&#39;]
>>> dir(&#39;jeff&#39;)
[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__iter__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;capitalize&#39;, &#39;casefold&#39;, &#39;center&#39;, &#39;count&#39;, &#39;encode&#39;, &#39;endswith&#39;, &#39;expandtabs&#39;, &#39;find&#39;, &#39;format&#39;, &#39;format_map&#39;, &#39;index&#39;, &#39;isalnum&#39;, &#39;isalpha&#39;, &#39;isdecimal&#39;, &#39;isdigit&#39;, &#39;isidentifier&#39;, &#39;islower&#39;, &#39;isnumeric&#39;, &#39;isprintable&#39;, &#39;isspace&#39;, &#39;istitle&#39;, &#39;isupper&#39;, &#39;join&#39;, &#39;ljust&#39;, &#39;lower&#39;, &#39;lstrip&#39;, &#39;maketrans&#39;, &#39;partition&#39;, &#39;replace&#39;, &#39;rfind&#39;, &#39;rindex&#39;, &#39;rjust&#39;, &#39;rpartition&#39;, &#39;rsplit&#39;, &#39;rstrip&#39;, &#39;split&#39;, &#39;splitlines&#39;, &#39;startswith&#39;, &#39;strip&#39;, &#39;swapcase&#39;, &#39;title&#39;, &#39;translate&#39;, &#39;upper&#39;, &#39;zfill&#39;]
>>> dir(&#39;abc&#39;)  File "<stdin>", line 1
    dir(&#39;abc&#39;)
       ^
SyntaxError: invalid character in identifier注意括号要英文下的括号

Attributes and methods similar to __xxx__ have special uses in Python, such as the __len__ method returning the length. In Python, if you call the len() function to try to get the length of an object, in fact, inside the len() function, it automatically calls the __len__() method of the object, so the following code is equivalent :

>>> len(&#39;asd&#39;)
3
>>> &#39;asd&#39;.__len__()
3

The rest are ordinary attributes or methods, such as lower() returns a lowercase string:

>>> &#39;ASDD&#39;.lower()
&#39;asdd&#39;

It is not enough to just list the attributes and methods, cooperate with getattr() , setattr() and hasattr(), we can directly manipulate the state of an object:

>>> class MyObject(object):
...     def __init__(self):
...         self.x = 9
...     def power(self):
...         return self.x*self.x
>>>
>>> obj = MyObject()
>>> hasattr(obj,&#39;x&#39;)
True
>>> obj.x
9
>>> hasattr(obj,&#39;y&#39;)
False
>>> setattr(obj,&#39;y&#39;,19)
>>> hasattr(obj,&#39;y&#39;)
True
>>> getattr(obj,&#39;y&#39;)
19

If you try to obtain a non-existent attribute, an AttributeError will be thrown:

>>> getattr(obj,&#39;Z&#39;)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: &#39;MyObject&#39; object has no attribute &#39;Z&#39;
>>>

You can pass in a default parameter. If the attribute does not exist, it will return to the default value:

>>> getattr(obj,&#39;Z&#39;,404)
404

You can also get the method of the object:

>>> hasattr(obj, &#39;power&#39;) # 有属性&#39;power&#39;吗?
True
>>> getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn = getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;并赋值到变量 fn
>>> fn # fn 指向 obj.power
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn() # 调用 fn()与调用 obj.power()是一样的
81

Related recommendations:

Python object-oriented inheritance and polymorphism

Python object-oriented access restrictions

Python object-oriented classes and instances













##

The above is the detailed content of Python object-oriented obtaining object information. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.