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?
First, we determine the object type, using the type() function:
Basic types can be judged using type():
>>> type(123) <class 'int'> >>> type('jeff') <class 'str'> >>> type(True) <class 'bool'> >>> type(None) <class 'NoneType'>
If a variable points to a function or class, you can also use type() to determine:
>>> type(abs) <class 'builtin_function_or_method'>
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('jeff') == type('1993') True >>> type('jeff') == str True >>> type(123) == int True >>> type(123) == type('jeff') 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('Animal is running...') class Dog(Animal): def run(self): print('Dog is haha running...') def eat(self): print('Eating meat...') class Cat(Animal): def run(self): print('Cat is miaomiao running...') def eat(self): print('Eating fish...') class Husky(Dog): def run(self): print('Husky is miaomiao running...') 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('a',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
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) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__pmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floorp__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rpmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloorp__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruep__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truep__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] >>> dir('jeff') ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir('abc') File "<stdin>", line 1 dir('abc') ^ 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('asd') 3 >>> 'asd'.__len__() 3
The rest are ordinary attributes or methods, such as lower() returns a lowercase string:
>>> 'ASDD'.lower() 'asdd'
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,'x') True >>> obj.x 9 >>> hasattr(obj,'y') False >>> setattr(obj,'y',19) >>> hasattr(obj,'y') True >>> getattr(obj,'y') 19
If you try to obtain a non-existent attribute, an AttributeError will be thrown:
>>> getattr(obj,'Z') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'MyObject' object has no attribute 'Z' >>>
You can pass in a default parameter. If the attribute does not exist, it will return to the default value:
>>> getattr(obj,'Z',404) 404
You can also get the method of the object:
>>> hasattr(obj, 'power') # 有属性'power'吗? True >>> getattr(obj, 'power') # 获取属性'power' <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>> >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量 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!