Home > Article > Backend Development > Python Advanced __attr__ Object Attribute
Everything in Python is an object, and each object may have multiple attributes. Python's attributes have a unified management scheme.
The attributes of an object may come from its class definition, which is called a class attribute.
Class attributes may come from the class definition itself, or they may be inherited from the class definition.
The attributes of an object may also be defined by the object instance, which are called object attributes.
The properties of an object are stored in the __dict__ attribute of the object.
__dict__ is a dictionary, the key is the attribute name, and the corresponding value is the attribute itself. Let's look at the classes and objects below.
Corresponds to Java's reflection to obtain the attributes of the object, such as:
public class UserBean { private Integer id; private int age; private String name; private String address; } //类实例化 UserBean bean = new UserBean(); bean.setId(100); bean.setAddress("武汉"); //得到类对象 Class userCla = (Class) bean.getClass(); //得到类中的所有属性集合 Field[] fs = userCla.getDeclaredFields(); ......
class bird(object): feather = True class chicken(bird): fly = False def __init__(self, age): self.age = age summer = chicken(2) print(bird.__dict__) print(chicken.__dict__) print(summer.__dict__)
Output:
{'__dict__': 5291f3363af48cec60c24e36c4754c66, '__module__': '__main__', ' __weakref__': 6c3eb635381693d08e835a3413d360c5, 'feather': True, '__doc__': None}
{'fly': False, '__module__': '__main__', '__doc__': None , '__init__': c51d1476b57e7fe91e8dedc84c3b2a0c}
{'age': 2}
The first line is the attribute of the bird class, such as feather.
The second line is the attributes of the chicken class, such as fly and __init__ methods.
The third line is the attribute of the summer object, which is age.
Some attributes, such as __doc__, are not defined by us, but are automatically generated by Python. In addition, the bird class also has a parent class, which is the object class (just like our bird definition, class bird(object)). This object class is the parent class of all classes in Python.
That is, the attributes of the subclass will override the attributes of the parent class.
You can modify the properties of a class through the following 2 methods:
summer.__dict__['age'] = 3 print(summer.__dict__['age']) summer.age = 5 print(summer.age)
property in Python
There may be dependencies between different properties of the same object. When a property is modified, we want other properties that depend on that property to change at the same time. At this time, we cannot statically store attributes through __dict__. Python provides several ways to generate properties on the fly. One of them is called a property.
class bird(object): feather = True #extends bird class class chicken(bird): fly = False def __init__(self, age): self.age = age def getAdult(self): if self.age > 1.0: return True else: return False adult = property(getAdult) # property is built-in summer = chicken(2) print(summer.adult) summer.age = 0.5 print(summer.adult)
The functionality here is similar to a trigger. Every time the adult attribute is obtained, the value of getAdult will be triggered.
Features are created using the built-in function property(). property() can load up to four parameters. The first three parameters are functions, which are used to process query characteristics, modify characteristics, and delete characteristics respectively. The last parameter is the document of the feature, which can be a string for description.
class num(object): def __init__(self, value): self.value = value print '<--init' def getNeg(self): print '<--getNeg' return self.value * -1 def setNeg(self, value): print '<--setNeg' self.value = (-1) * value def delNeg(self): print("value also deleted") del self.value neg = property(getNeg, setNeg, delNeg, "I'm negative") x = num(1.1) print(x.neg) x.neg = -22 print(x.value) print(num.neg.__doc__) del x.neg
During the entire process, the corresponding functions were not called.
In other words, the creation, setting, and deletion of the neg attribute are all registered through property().
Python special method __getattr__ (this is commonly used)
We can use __getattr__(self, name) to query the attributes generated on-the-fly.
In Python, object attributes are dynamic, and attributes can be added or deleted at any time as needed.
Then the function of getattr is to perform a layer of judgment processing when generating these attributes.
For example:
class bird(object): feather = True class chicken(bird): fly = False def __init__(self, age): self.age = age def __getattr__(self, name): if name == 'adult': if self.age > 1.0: return True else: return False else: raise AttributeError(name) summer = chicken(2) print(summer.adult) summer.age = 0.5 print(summer.adult) print(summer.male)
Each feature needs its own processing function, and __getattr__ can handle all instant generated attributes in the same function. __getattr__ can handle different attributes based on the function name. For example, when we query the attribute name male above, we raise AttributeError.
(There is also a __getattribute__ special method in Python, which is used to query any attribute.
__getattr__ can only be used to query attributes that are not in the __dict__ system)
__setattr__(self, name, value) and _ _delattr__(self, name) can be used to modify and delete attributes.
They have a wider range of applications and can be used for any attribute.