Home > Article > Backend Development > How to get all properties of an object in Python
Using reflection in Python, we can get all the attributes of an object. This mechanism is called reflection (which in turn lets the object tell us what it is) and is used to obtain information about unknown objects at runtime.
The following are several built-in methods that can be used to check or access the properties of an object. These methods can be used on any object, not just the Cat instance object in the example;
#coding:utf-8 from a import * cat = Cat('kitty') print cat.name cat.sayHi() #调用实例方法 print dir(cat) if hasattr(cat, 'name'): #检查实例是否有这个属性 setattr(cat, 'name', 'tiger') #same as: a.name = 'tiger' print getattr(cat, 'name') #same as: print a.name getattr(cat, 'sayHi')()
dir([obj]):
Call this method Will return a list containing most of the attribute names of obj (there will be some special attributes that are not included). The default value of obj is the current module object.
hasattr(obj, attr):
This method is used to check whether obj has an attribute named attr and returns a Boolean value.
getattr(obj, attr):
Calling this method will return the value of the attribute named attr value in obj. For example, if attr is 'bar', obj.bar will be returned.
setattr(obj, attr, val):
Calling this method will assign the value of obj’s attribute named attr to val. For example, if attr is 'bar', it is equivalent to obj.bar = val.
The above is the detailed content of How to get all properties of an object in Python. For more information, please follow other related articles on the PHP Chinese website!