access to python object properties

After reading the big chapter of fluent python's metaprogramming, let's summarize the feelings after reading.

 

The first is 4 protocols about object property access

According to understanding, it can be divided into

__getattribute__         

and

__getattr__        __setattr__      __delattr__

This division is because the __getattribute__ method will only be executed when the object has the attribute and needs to get a certain attribute value of the object. This method can be understood as a read-only attribute. I think this is why it and other The reason why the three methods have different names

__getattr__ will be executed when the attribute is not found, __setattr__ is used to add an attribute, and __delattr__ is used to delete an attribute.

 

 

 

Then property and descriptor

The reason for these is that when you want to access object properties, you can control the process of object properties get, set, and del

 

Property is the descriptor that comes with the python language, so its function is not customized enough, and some of the advantages of classes (for example, classes can be inherited, classes can have class attributes) are not supported by these properties.

So on the basis of property, there is a descriptor

 

 

 

 

And finally the metaclass

This is because in some scenarios such as ORM, validator in Django, people want to be able to control the attributes of the class

1. The first method that comes to mind is class decorator, but the disadvantage of this method is that this method is based on functions, so it is not like class can inherit

2. Then people thought of metaclass,

   First of all, it is clear that type is a metaclass that comes with the python language. When declaring a class, the mechanism behind it is type(classname, bases, attr_dict), and behind it is the metaclass of type that generates the class 

   But because type is built-in, it is obviously not customizable, so sometimes people need to write their own metaclass

    The metaclass written by myself inherits type, so it inherits the ability of type to create class (I think this is the meaning of inheritance: subclass can inherit the ability of parent class)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325346004&siteId=291194637