Some concepts based on descriptor in Python (above)

Source: Internet
Author: User

Some concepts based on descriptor in @python (the above)

      • some concepts based on descriptor in Python (top)
        • 1. Preface
        • 2. New class and Classic class
          • 2.1 built-in object objects
          • 2.2 Methods of class
            • 2.2.1 Static methods
            • 2.2.2 class methods
          • 2.3 New Class (New-style Class)
            • 2.3.1 __init__ method
            • 2.3.2 __new__ static method
          • 2.4. Example of a new class
            • 2.4.1 Property
            • 2.4.2 __slots__ Properties
            • 2.4.3 __getattribute__ method
            • 2.4.4 instance Method
          • 2.5 New object Model
            • 2.5.1 Multiple inheritance
            • 2.5.2 MRO (method Resolution order, methods parse sequence)
            • 2.5.3 Cooperative call to Parent class method
Some concepts based on descriptor in Python (1). Preface Python introduced the Descriptor feature in version 2.2, and it is precisely this feature that implements the object model of the new Class (New-styel Class) and addresses the MRO in multiple inheritance in the classic class system in previous versions (Method Resolution Order), and introduces some new concepts, such as Classmethod, Staticmethod, Super,property, and so on, these new functions are based on descriptor. To summarize, learn more about how Python works by learning descriptor. I'll probably write a summary of this and write a comprehension of these things. You are welcome to discuss. Here is a description of the vocabulary used in the article:Function: Refers to a function where the first argument is not self, not a function defined in a classmethod: Refers to the function where the first argument is selfExample: Object of class, instanceObject Model: is the entire framework for implementing object behavior, which is divided into two classical and newThe python version used is Python 2.7.22. New class and classic class first to understand the difference between the new class and the classic class, from the creation method can be clearly seen:#新式类
class C (object):
Pass
#经典类
class B:
Pass Simply put, the new class inherits the built-in object objects (either from built-in types, such as list,dict, etc.), while the classic class is directly declared. Using the Dir () method, you can also see that many new properties and methods are defined in the modern class, while the classic class seems to be 2: The new properties and methods are inherited from the object objects. 2.1 Built-in object objects are built-in object objects that are all built-in, object objects define a series of special methods to implement the default behavior of all objects. 1. __new__,__init__ method These two methods are used to create a subclass object for object, the static method __new__ () is used to create an instance of the class, and then call __INIT__ () to initialize the instance. 2. __delattr__, __getattribute__, __setattr__ method objects use these methods to handle access to the property 3. __hash__, __repr__, __str__ method Print (someobj) calls someobj.__str__ (), and if __str__ is not defined, someobj.__repr__ (), __str__ (), and _ are called. The difference between _repr__ ():
    • The default implementation is of no effect
    • The goal of __REPR__ is the uniqueness of object information
    • The goal of __str__ is the readability of object information
    • The __str__ of a container object typically uses the __repr__ of an object element
    • If __REPR__ is redefined and no __str__ is defined, the __repr__ is called when __str__ is called by default
    • In other words, a good programming habit is that every class needs to rewrite a __repr__ method to provide the object's readable information.
    • Overriding the __str__ method is optional. Implementing the __str__ method generally requires a better looking print effect, such as you want to make
    • A report, and so on.
You can allow subclasses of object to overload these methods, or add new methods. Methods of class 2.2 The new object model provides two classes of methods, static methods and class methods, and in many of the characteristics of new classes, only the class method, which is the same functionality as the classic object model. 2.2.1 Static method static method can be called by a class or instance, it does not have the usual method of behavior (such as binding, non-binding, the default first self parameter), when there are a bunch of functions just for a class write, the static method is declared within the class, you can provide behavioral consistency. The code for creating a static method is as followscreate using the adorner @staticmethod:As you can see, whether it's a class call or an instance call to a static method, it is a pointer to the same function object 2.2.2 class method can also be called through the class and its instance, but it has the default first parameter, called the class object, is generally named CLS, of course you can also name other names, So you can invoke some of the actions of the class object, the code is as follows,create using the adorner @classmethod:2.3 The new Class (New-style Class) Modern class has some features in addition to all the features of the classic class. For example, __INIT__ has changed, the new static method __new__2.3.1 __init__ method is said that before the python2.4 version, when using the new class, if the class initialization method is not defined, when the call to write extra parameters, the compiler will not error. I now Python 2.7 will be an error, or I think the error is better, the following gives the new class and classic class run this example of the case: 2.3.2 __new__ static method The new class has a __new__ static method, its prototype isobject.__new__ (cls[, ...])The CLS is a class object, and when you call C (*args, **kargs) to create an instance of Class C, the internal invocation of Python is c.__new__ (c, *args, **kargs), and then the return value is instance C of Class C, after confirming that C is an instance of C, Python then calls c.__init__ (C, *args, **kargs) to initialize instance C. So call an instance c = C (2) and actually execute the code: C= c.__new__ (C, 2)
if isinstance(c, c):
C. __init__(c, 23°c)#__init__第一个参数要为实例对象 Object.__new__ () Creates a new instance that is not initialized. When you override the __new__ method, you can not use the adorner @staticmethod to indicate that it is a static function, and the interpreter will automatically judge this method as a static method. If you need to rebind the c.__new__ method, simply perform c.__new__ = Staticmethod (Yourfunc) outside the class. You can use __new__ to implement Singleton Singleton mode: classSingleton (object):
_singletons= {}
def__NEW__ (CLS):
         if not cls._ Singletons.has_key (CLS) :              #若还没有任何实例
         &NBSP;&NBSP;&NBSP;&NBSP;CLS._SINGLETONS[CLS] = object.__new__ (CLS)   < Span style= "color: #008000;" > #生成一个实例
         return cls._singletons[cls]                               #返回这个实例 The result is as follows: using the ID () operation, you can see two instances pointing to the same memory address. All subclasses of Singleton also have this attribute, there is only one instance object, if its subclass defines the __init__ () method, then it must be ensured that its __init__ method is safe to make multiple calls to the same instance. 2.4. Examples of modern classes have new features in addition to the new classes themselves, and the instances of modern classes. For example, it has a property function, which affects how properties are accessed, and __slots__ new properties that affect the generation of subclass instances, and a new method __getattribute__, which is more generic than the original __getattr__. 2.4.1 property at the end of the introduction descriptor will return to this. The 2.4.2 __slots__ property usually has a __dict__ attribute for each instance of X, which is used to record all the properties and methods in the instance, and the dictionary allows the instance to bind arbitrary attributes. The __slots__ property function is that when class C has fewer variables, and the __slots__ attribute is present, the instance of Class C has no __dict__ attribute, but the value of the variable exists in a fixed place. If you try to access a property that is not in a __slots__, the instance will get an error. What is the benefit of doing so? Although the __slots__ property makes the instance lose the convenience of binding any property, but because each instance has no __dict__ attribute, it can save the memory consumption of each instance effectively, and it is advantageous to produce small and lean instance.Why do you need such a design? In a real enterprise application, it is worthwhile to use the __slots__ property when a class generates millions of instances, saving a large amount of memory even if one instance saves dozens of bytes. How to define the __slots__ attribute?
__SLOTS__ is a class variable, and the __slots__ property can assign a string tuple that contains the class property name, or it can be an iterative variable or a string, as long as the class is defined, using the __slots= Atuple to define this property: You can see that there is no __dict__ dictionary in instance A, and you cannot add new properties at will, and do not define __slots__ as you can add: some points to be aware of when using __slots__:1.  When the parent class of a class does not have a __slots__ attribute defined, the __dict__ property in the parent class is always accessible, so it is meaningless to define the __slots__ attribute only in the subclass, not in the parent class.  2. If you define the __slots property, or if you want to add a new variable later, you need to add the ' __dict__ ' string to the __slots__ 's tuple.  3. A property that defines the __slots__ property is __weakref__, so the weak reference of the instance is not supported, and if you still want to use this function, you can add the ' __weakref__ ' string to the tuple as well.  4. The __SLOTS__ feature is implemented through descriptor and creates a descriptor for each variable.  5. The __SLOTS__ function only affects the class that defines it, so the subclass needs to redefine __slots__ to have its function. 2.4.3 __getattribute__ method For instance of a new class, all properties and methods are accessed through __GETATTRIBUTE__, which is implemented by the object base class. If you have special requirements, you can overload the __getattribute__ method, implementing a list:  2.4.4 that cannot use the Append method The methods of the instance classic and the new object model both allow an instance to have private properties and methods (which can be bound and re-bound). The private property of the instance overrides the attribute with the same name defined in the class, for example:  However, in Python, the new object model and the classic object model behave differently when the private special method of an instance is implicitly invoked. In the Classic object model, a special method that is bound after the instance is invoked, whether it is a display call or an implicit invocation of a particular method. In the new object model, unless you explicitly invoke the special method of the instance, Python will always call the special method defined in the class, and if there is no definition, an error. The code is as follows: Classic class:  new class:   call a[1], will produce an implicitThe invocation of the __getitem__ method, in the new class, is an error because the method is not defined in the class and is not a method of the object base class. It needs to be displayed to be called before it can run. 2.5 The new object model, in the new object model, inherits in much the same way as the classic object model, and one key difference is that the new class can inherit from Python's built-in type, and the classic class does not. 2.5. More than 1 inheriting modern classes also support multiple inheritance, but if the modern class wants to inherit from multiple built-in types to generate a new class, then these built-in classes must be well-designed and compatible with each other. Obviously, Python doesn't make you arbitrarily inherit from multiple built-in classes, and it's not that easy to create a super-class ... Typically, you can inherit at most one built-in class, such as List, set, Dict, and so on. 2.5.2 MRO (method Resolution order, methods parsing sequence) for multiple inheritance relationships: b = A (), what happens when you call B.A? In the Classic object model, the lookup chain of methods and properties is found in a way that is left-to-right and depth-first. So when instance B of a is going to use attribute A, it looks in the order: A->b->d->c->a, which ignores the definition of class C A, and first finds the attribute a of base class D, which is a bug that is fixed in the new class. The new object model takes a left-to-right, breadth-first approach to finding, so the lookup order is a->b->c->d, which returns the property A of class C correctly. Classic class: New class:   The implementation of this order is through the special read-only attribute __mro__ in the new class, the type is a tuple, which holds the parsing order information. Can only be used by a class and cannot be called through an instance. The order is also related to the order in which the parent class is written in parentheses: 2.5.3 cooperative invocation of a parent class method when a subclass overrides a method of a parent class, it is common to call the parent class with the same name method to do some work, which is a more commonly used method of calling the parent class using the unbound syntax. However, in multiple inheritance, this method has a missing stuffing: you can see that the method of base class A repeats two times. How do you make sure that the methods in the parent class are called only once in order? In the new object system, there is a special way of super (AClass, obj), which can return a special type of superobject of the obj instance (a superclass, not an object of a simple parent class), when we use a superclass to invoke the method of the parent class. can be guaranteed to run only once: as you can see, all Foo methods in the parent class of D are executed, and the Foo method of base Class A executes only once. If you develop the habit of using super to invoke the parent class method, then yourClasses can accommodate no matter how complex the inheritance call structure. Super () can be seen as a new way to call the parent class method more securely.   

Some concepts based on descriptor in Python (above)

Related Article

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.