Python delves into the properties of objects

  • 2020-04-02 14:02:26
  • OfStack

Python is all objects, and each object may have multiple attributes. Python's properties have a unified management scheme.

Attribute of the system of s

The attributes of an object may come from its class definition, called a class attribute. Class attributes may be derived from the class definition itself or inherited from the class definition. An object's attributes may also be defined by the object instance, called object attribute.

The properties of the object are stored in the s/s s of the object. S/s is a dictionary with the key as the property name and the value as the property itself. Let's look at the following classes and objects. The chicken class inherits from the bird class, and summer is an object of the chicken class.


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__)

 

The following is our output result:


{'__dict__': <attribute '__dict__' of 'bird' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'bird' objects>, 'feather': True, '__doc__': None}
{'fly': False, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x2b91db476d70>}
{'age': 2}

The first behavior is an attribute of the bird class, such as feather. The second action is the attributes of the chicken class, such as fly and the cascade method. The third behavior is a property of the summer object, which is age. Some of the properties, such as s/s, are not defined by us, but are generated automatically by Python. In addition, the bird class also has a parent class, which is the object class (as our bird definition, class bird(object)). This object class is the parent of all classes in Python.

As you can see, in Python attributes is defined hierarchical, as here is divided into the object/bird/chicken/summer this four layers. When we need to call a property, Python iterates up the hierarchy until we find that property. (an attribute may be repeatedly defined in different layers, and as Python moves up, it selects the one encountered first, i.e. the lower level attribute definition.)

When we have a summer object, we can query the properties of the summer object, the chicken class, the bird class and the object class respectively, and then we can know all the s of the summer object. Then we can find all the properties that can be called and modified by the summer object. The following two property modification methods are equivalent:


summer.__dict__['age'] = 3
print(summer.__dict__['age']) summer.age = 5
print(summer.age)

  (in the above case, we already know that the class of the summer object is chicken, and the parent of the chicken class is bird. If there is only one object and no class or other information is known, we can find the class of the object by using the s * * * * * ss * * * s * * s * * s and then call the s * * * ss * * * s to query the parent class.

features

There may be dependencies between different properties of the same object. When an attribute is modified, we want other attributes that depend on that attribute to change as well. At this time, we cannot statically store the attributes by means of arbitration. Python provides a variety of methods for generating attributes on the fly. One is called a property. A property is a special property. Let's say we add an adult to the chicken class. When the age of an object exceeds 1, adult is True; Otherwise False:


class bird(object):
    feather = True 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)

Properties 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 handle query feature, modify feature and delete feature respectively. The last parameter is a feature document, can be a string, to illustrate.

We use the following example to further illustrate:


class num(object):
    def __init__(self, value):
        self.value = value
    def getNeg(self):
        return -self.value
    def setNeg(self, value):
        self.value = -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

The num above is a number and the neg is a property used to represent the negative of a number. When a number is fixed, its negative number is always fixed; And when we change the negative value of a number, the value itself should change. These two points are implemented by getNeg and setNeg. DelNeg, on the other hand, means that if you delete the property neg, what you should do is delete the property value. The last parameter of the property() ("I'm negative") is the attribute negative.

Use the special method of successive getattr__

We can use arbitration getattr__(self, name) to query the immediately generated attribute. When we query for an attribute, if the attribute cannot be found with the s/s method, Python calls the s/s method of the object to generate the attribute immediately. Such as:


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 to have its own handler, and with successive getattr__ all immediate build attributes can be processed in the same function. You can handle different attributes depending on the function name. For example, when we query the attribute name male above, raise AttributeError.

(there is also a special method in Python to query arbitrary attributes with getattribute__. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. They are more versatile and can be used for arbitrary properties.

Other ways to generate properties on the fly

There are other ways to generate properties in real time, such as descriptors (the descriptor class is actually the bottom of the property() function, and property() actually creates an object for that class). You may refer to it further if you are interested.

conclusion

S hierarchical storage properties. S/s per tier stores only the newly added properties of that tier. Subclasses do not need to store attributes in the parent class repeatedly.

Just-in-time generation properties are a concept worth understanding. In Python development, you might use this approach to manage the properties of objects more reasonably.


Related articles: