Home > Backend Development > Python Tutorial > Python object-oriented obtaining object information

Python object-oriented obtaining object information

不言
Release: 2018-04-14 10:28:11
Original
1632 people have browsed it

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;>
Copy after login

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;>
Copy after login

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
Copy after login

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
Copy after login

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()
Copy after login
Dog is haha running...
Eating meat...
Husky is miaomiao running...
Cat is miaomiao running...
Eating fish...
Copy after login

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))
Copy after login
True
True
True
True
True
True
Copy after login
print(isinstance(d,Husky))
False
Copy after login

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
Copy after login

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;]
Copy after login
>>> dir(&#39;abc&#39;)  File "<stdin>", line 1
    dir(&#39;abc&#39;)
       ^
SyntaxError: invalid character in identifier注意括号要英文下的括号
Copy after login

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
Copy after login

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

>>> &#39;ASDD&#39;.lower()
&#39;asdd&#39;
Copy after login

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
Copy after login

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;
>>>
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template