Some descriptor-based concepts in python (I)

Source: Internet
Author: User

    • Some descriptor-based concepts in python (I)
      • 1. Preface
      • 2. New and classic categories
        • 2.1 built-in object
        • Methods of the 2.2 class
          • 2.2.1 static method
          • 2.2.2 Class Methods
        • 2.3 new style class)
          • 2.3.1 _ init _ Method
          • 2.3.2 _ new _ static method
        • 2.4. New Class instances
          • 2.4.1 Property
          • 2.4.2 _ slots _ attributes
          • 2.4.3 _ getattribute _ Method
          • 2.4.4 instance method
        • 2.5 New Object Model
          • 2.5.1 multi-Inheritance
          • 2.5.2 MRO (Method Resolution Order, Method Resolution Order)
          • 2.5.3 collaborative calling of parent Methods
Some descriptor-based concepts in python (I) 1. Preface

Python 2.2 introduces the descriptor function, which is based on the new-styel class object model. It also solves the classic class in earlier versions) the MRO (Method Resolution Order) Problem in multiple inheritance occurs in the system, and introduces some new concepts, such as classmethod, staticmethod, super, Property, etc, these new features are implemented based on descriptor. To sum up, you can learn more about the running mechanism of python by learning descriptor. Here I will also write a summary about my understanding of these things. Welcome to the discussion. Here, I will explain the words used in the article: function: refers to the function that is not self in the first parameter and is not defined in the class: the first parameter is the function instance of self: the object of the class. The instance object model is the entire framework that implements object behavior, the python version is classic and new. The python version is python 2.7.22. the new class and the classic class first come to understand the differences between the new class and the classic class. From the creation method, we can clearly see: # New Class
ClassC (object ):
Pass
# Classic
ClassB:
PassSimply put, the new class inherits the built-in object objects (or from the built-in types, such as list and dict) during creation, while the classic class is directly declared. Using the dir () method, we can see that many new attributes and methods are defined in the new class, and the classic class seems to have two: these new attributes and methods are inherited from the object. 2.1 The built-in object objects are all built-in objects. The object defines a series of special methods to implement the default behavior of all objects. 1. the _ new __,__ init _ method is used to create a subclass object of the object. The static method _ new _ () is used to create an instance of the class, then, call _ init _ () to initialize the instance. 2. _ delattr __, _ getattribute __, _ setattr _ method objects use these methods to process attribute access 3. _ hash __, _ repr __, _ str _ method print (someobj) will call someobj. _ str _ (). If _ str _ is not defined, someobj is called. _ repr _ (), _ str _ () and _ repr _ () are different:
  • The default implementation has no effect.
  • _ Repr _ aims to ensure the uniqueness of object information.
  • The objective of _ str _ is the readability of object information.
  • The _ str _ of the container object generally uses the _ repr _ of the object element __
  • If _ repr __is redefined, but _ str __is not defined, _ repr _ is called by default when _ str _ is called __
  • That is to say, a good programming habit is that every class needs to rewrite a _ repr _ method to provide object readable information,
  • The rewrite _ str _ method is optional. Implementation of the _ str _ method usually requires better print effects. For example
  • A report.
You can allow subclass objects to overload these methods or add new methods. 2.2 class methods the new object model provides two types of methods, static methods and class methods. Among the features of many new classes, there is only the class method feature, it provides the same functions as the classic object model. 2.2.1 static methods can be called by classes or instances. They do not act as common methods (such as binding, non-binding, the default first self parameter ), when a bunch of functions are only written for a class, they are declared inside the class using static methods, which can provide behavior consistency. The code for creating a static method is as follows: Use the modifier @ staticmethod to create a static method: You can see whether it is a class call or an instance call a static method, both point to the same function object 2.2.2 Class methods can also be called through the class and its instance, but it has the default first parameter, called a class object, which is generally named cls, of course, you can also name it another name, so that you can call some operations on the class object. The Code is as follows, using the modifier @ classmethod to create: 2.3 new class (new-style class) in addition to all the features of classic classes, new classes also have some new features. For example, if _ init _ is changed, the static method _ new _ 2.3.1 _ init _ is added. It is said that when the new class is used before python2.4, if the class initialization method is not defined and redundant parameters are written during the call, the compiler will not report an error. I still think it would be better to report errors in python 2.7. The following shows an example of running the new and classic classes: 2.3.2 _ new _ static method the new class has a static method of _ new _. Its prototype is object. _ new _ (cls [,...]) cls is a Class Object. When you call C (* args, ** kargs) to create a class C instance, the internal call of python is C. _ new _ (C, * args, ** kargs). Then, the returned value is instance C of class c. After confirming that c is an instance of class C, python calls C. _ init _ (c, * args, ** kargs) to initialize instance c. So the actual code for calling an instance c = C (2) is: c = C. _ new _ (C, 2)
If Isinstance(C, C ):
C. _ Init __(C, 23) #__ init _ the first parameter creates a new instance for the Instance object. _ new. When you override the _ new _ method, you do not need to use the modifier @ staticmethod to indicate that it is a static function. The Interpreter automatically determines that this method is a static method. If you need to re-bind the C. _ new _ method, you only need to execute C. _ new _ = staticmethod (yourfunc) outside the class. The Singleton mode can be implemented using _ new: ClassSingleton (object ):
_ Singletons = {}
Def_ New _ (cls ):
If NotCls. _ singletons. has_key (cls): # If no instance exists
Cls. _ singletons [cls] = object. _ new _ (cls) # generate an instance
ReturnCls. _ singletons [cls] # Return the instance running result as follows: Use id () operation, you can see that the two instances point to the same memory address. All subclasses of Singleton also have this feature. There is only one instance object. If its subclass defines the _ init _ () method, therefore, the _ init _ method must be safe for multiple calls to the same instance. 2.4. In addition to new features, new class instances also have new features. For example, if it has the Property function, this function will affect the access method of the Property; and the new _ slots _ attribute will affect the generation of subclass instances; a new method _ getattribute __is added, which is more common than the original method _ getattr. 2.4.1 after descriptor is introduced, Property will go back and talk about this. 2.4.2 _ slots _ attributes each instance x usually has a _ dict _ attribute, which is used to record all attributes and methods of the instance, you can bind an instance to any attribute. The _ slots _ attribute is used when class C has fewer variables and has the _ slots _ attribute, A Class C instance does not have the _ dict _ attribute, but stores the variable value in a fixed place. If you try to access a property not found in _ slots _, an error is returned for the instance. What are the advantages of this operation? Although the _ slots _ attribute makes the instance lose the convenience of binding any attribute, it can effectively save the memory consumption of each instance because each instance does not have the _ dict _ attribute, it is conducive to generating small and lean instances. Why do we need such a design? In an enterprise-level application, when a class generates millions of instances, even if an instance saves dozens of bytes, it can save a lot of memory, in this case, the _ slots _ attribute is worth using. How to define the _ slots _ attribute?
_ Slots _ is a class variable, where the _ slots _ attribute can assign a value to a string that contains the class name, or an iteratable variable or a string, you only need to use _ slots = aTuple to define this attribute when defining a class: we can see that there is no _ dict _ dictionary in instance, in addition, you cannot add new properties at will. If you do not define _ slots _, you can add the following items: 1. when the _ slots _ attribute is not defined for the parent class of a class, the _ dict _ attribute in the parent class is always accessible, therefore, it is meaningless to define the _ slots _ attribute in the subclass rather than in the parent class. 2. if you have defined the _ slots attribute and want to add a new variable later, you need to add the '_ dict _' string to the _ slots _ tuples. 3. when the _ slots _ attribute is defined, the _ weakref __will disappear. In this way, the instance's weak reference is not supported. If you still want to use this function, you can add the '_ weakref _' string to the tuples. 4. The _ slots _ function is implemented by the descriptor. A descriptor is created for each variable. 5. The _ slots _ function only affects the class that defines it. Therefore, the subclass must be redefined _ slots _ to have its function. 2.4.3 _ getattribute _ Method for instances of the new class, access operations for all attributes and methods are completed through _ getattribute _, which is implemented by the object base class. If you have special requirements, you can overload the _ getattribute _ method. The following is a list that cannot use the append method: 2.4.4 instance methods classic and new object models allow an instance to have private attributes and methods (through binding and rebinding ). The private attributes of an instance overwrite the attributes of the same name defined in the class. For example, in python, when an instance's private special method is called implicitly, the new object model is not the same as the classic object model. In the classic object model, both the display call and the implicit call of special methods call the special methods bound to the instance. In the new object model, unless the special method of the instance is explicitly called, python always calls the special method defined in the class. If the method is not defined, an error is returned. The Code is as follows: Classic class: New Class: calling a [1] will generate an implicit _ getitem _ method call. In the new class, because this method is not defined in the class, and it is not a method of the object base class, an error is returned. It can be run only when it is displayed and called. 2.5 In the new object model, the inheritance method is roughly the same as that in the classic object model. A key difference is that the new class can be inherited from the built-in python type, the classic category does not work. 2.5.1 multiple inheritance new classes also support multiple inheritance, but if the new class wants to inherit from multiple built-in classes to generate a new class, these built-in classes must be carefully designed, compatible with each other. Obviously, python does not allow you to inherit from multiple built-in classes at will. It is not that easy to create a super class... Generally, you can inherit at most one built-in class, such as list, set, and dict. 2.5.2 multi-inheritance relationship for MRO (Method Resolution Order, Method Resolution Order): B = A (). What happens when B. a is called? In the classic object model, the Search links for methods and attributes are left-to-right, with depth given priority. So when instance B of A uses attribute a, its search order is: A-> B-> D-> C->, in this way, Class C's definition a will be ignored, and the attribute a of the base class D will be found first. This is a bug and this problem is fixed in the new class, the new object model uses the left-to-right and breadth-first search method, so the search order is A-> B-> C-> D, you can return the property a of class C correctly. Classic class: New Class: the implementation of this sequence is based on the special read-only attribute _ mro __in the new class. The type is a tuples and stores the parsing sequence information. It can only be used through classes and cannot be called through instances. The sequence is also related to the parent class sequence written in parentheses during inheritance: 2.5.3 collaborative calling of the parent class method when the subclass overrides a method of the parent class, the method of the parent class with the same name is usually called to do some work. This is a common method of using the non-binding syntax to call the method of the parent class. However, in multi-inheritance, this method is missing: we can see that the method of the base class A runs twice. How can we ensure that the methods in the parent class are called only once in sequence? In the new object system, there is a special method super (aclass, obj), which can return a special type superobject (superobject, is not a simple parent class object). When we use a superobject to call the parent class method, we can ensure that it is only run once: You can see that, all the foo methods in the parent class of D are executed, and the foo method of the base class A is only executed once. If you get into the habit of using super to call the parent class method, your class can adapt to no matter how complicated it is to inherit the call structure. Super () can be seen as a new way to call the parent class method more securely.

Publish by note

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.