Python built-in function (--super)

Source: Internet
Author: User
Tags class definition

English documents:

super([type[, object-or-type]])

Return a proxy object, delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that has been overridden in a class. The search order is same as, used by getattr() except, the type itself is skipped.

The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super() . The attribute is dynamic and can whenever, the inheritance hierarchy is updated.

If The second argument is omitted, the Super object returned is unbound. If The second argument is a object, isinstance(obj, type) must be true. If The second argument is a type, issubclass(type2, type) must are true (this is useful for classmethods).

There is typical use cases for Super. In a class hierarchy with single inheritance, Super can is used to refer to parent classes without naming them ex Plicitly, thus making the code more maintainable. This use closely parallels the use of Super in other programming languages.

The second use case was to support cooperative multiple inheritance in a dynamic execution environment. This is a unique to Python and are not found in statically compiled languages or languages Inheritance. This makes it possible to implement "diamond diagrams" where multiple base classes implement the same method. Good design dictates that this method has the same calling signature in every case (because the order of calls are Determi Ned at runtime, because this order adapts to changes in the class hierarchy, and because that order can include sibling cl Asses that is unknown prior to runtime).

Note that super ()  is implemented as part of the Binding process for explicit dotted attribute lookups such as super (). __getitem__ ( Name) . It does so by implementing It Own __getattribute__ ()  method for searching classes with a predictable order that supports cooperative multiple inheritance. Accordingly, super ()  is undefined for implicit Lookups using statements or operators such as super () [name] .

Also note, aside from the zero argument form, was not limited to use super() inside methods. The argument form specifies the arguments exactly and makes the appropriate references. The zero argument form has works inside a class definition, as the compiler fills in the necessary details to correctly r Etrieve the class being defined, as well as accessing the current instance for ordinary methods.

Generates a new subclass and a proxy object for the parent class relationship based on the parameters passed in

Description

1. The Super function returns a proxy object that can call the parent class of the class or the method of the sibling class without displaying the class name of the specified parent or sibling class.

2. Why do you have super?

Before the earliest, the method of calling the parent class (A) in subclass (B) was taken in the following way:

#定义父类A >>> class A (object):    def __init__ (self):        print (' a.__init__ ') #实例化A        >>> a = A () a._ _init__# defines subclass B, inherits a, calls A's __init__ method in the __init__ method of B >>> Class B (a):     def __init__ (self):        print (' b.__ init__ ')        a.__init__ (self) #实例化B >>> B = B () b.__init__a.__init__

Assuming that you now want to change the new definition of a class (A1) and change the inheritance relationship (B->a to B->A1), you need to make the following modifications in all classes:

#定义新的父类A1 >>> class A1 (object):    def __init__ (self):        print (' a1.__init__ ') #更改继承关系B->a to B->A1 >>> class B (A1):    def __init__ (self):        print (' b.__init__ ')        a1.__init__ (self) #能正确调用新的父类A1的__ init__ method >>> B = B () b.__init__a1.__init__# hypothesis forgot to modify a.__init__ (self) >>> Class B (A1):    def __init__ ( Self):        print (' b.__init__ ')        a.__init__ (self)      #则还是调用了A的__init__方法 >>> B = B () b.__init__a.__ init__

After introducing super, you do not need to display the class name of the specified parent class, which enhances the maintainability of the program:

#B->a use Super Mode to call the parent class method >>> class B (A):    def __init__ (self):        print (' b.__init__ ')        super (). __ init__ () #能正确调用父类方法 >>> B = B () b.__init__a.__init__# change the inheritance relationship B->a to B->A1, call the parent class method without modifying >>> class B (A1):    def __init__ (self):        print (' b.__init__ ')        super (). __init__ () #也能正确调用父类方法 >>> B = B () b.__ init__a1.__init__

3. A super with no parameters is equivalent to super (class name, self), which is used in subclasses of single-inheritance relationships.

#super不带参数 >>> class B (A1):    def __init__ (self):        print (' b.__init__ ')        super (). __init__ () # The parent class method can be called correctly >>> B = B () B.__init__a1.__init__#super with two parameters (class name, self) >>> Class B (A1):    def __init__ ( Self):        print (' b.__init__ ')        super (b,self). __init__ () #也能正确调用父类方法 >>> B = B () b.__init__a1.__init__

4. If the 2nd parameter is not passed in, it means that the proxy object does not bind the inheritance relationship.

#super第2个参数不传入, the build proxy object does not bind the inheritance relationship >>> Class B (A1):    def __init__ (self):        print (' b.__init__ ')        super (B ). __init__ () #super (B). The __init__ () method does not call the parent class method >>> B = B () b.__init__

5. If the 2nd parameter is an object, the object must be an instance of the 1th parameter of the specified type, which is used in subclasses of a multi-tier inheritance relationship.

#定义父类A >>> class A (object): Def __init__ (self): print (' a.__init__ ') #定义子类B, inheriting the __init__ method of calling the parent class in a,__init__ &G T;>> class B (A): def __init__ (self): print (' b.__init__ ') super (). __init__ () #定义子类C, calling the parent class in inheritance b,__init__ __init__ method >>> class C (B): def __init__ (self): print (' c.__init__ ') super (). __init__ () #实例 C, execute the __init__ method of C, call the __init__ method of the direct parent class B, and further call the indirect parent Class A's __init__ method >>> C = C () c.__init__b.__init__a.__init__#        Redefine subclass C, inheritance relationship unchanged, call parent class method __init__ instead of super (b,self) >>> class C (B): def __init__ (self): print (' c.__init__ ') Super (B,self). __init__ () #实例化C时, executes the __init__ method of C, the Super (B,self) agent finds the parent class A of B, converts self to an instance of B, calls the __init__ method of a directly, skips the call to B's __ Init__ method >>> C = C () c.__init__a.__init__# defines a new class D>>> class D (object): Def __init__ (self): print ( ' d.__init__ ') #重新定义C, the inheritance relationship is unchanged, call the parent class method __init__ instead of super (d,self) >>> class C (B): def __init__ (self): print (' C._ _init__ ') Super (d,self). __init__ () #实When C is instantiated, the __init__ method of C is executed, and the super (D,self) agent finds the parent object of D, converts self to the instance of D, because D and C have no inheritance relationship, and self cannot be converted to an instance of D so error >>> c= C () c.__ Init__traceback (most recent): File "<pyshell#14>", line 1, in <module> c= C () file "<pyshel L#13> ", line 4, in __init__ Super (d,self). __init__ () typeerror:super (type, obj): obj must is an instance or subtype of type

6. If the 2nd parameter is a type, the type must be a subclass of the 1th parameter of the specified type, which is used in subclasses of multi-tier inheritance relationships, and is applicable to class methods.

#定义父类A, and define a class method Sayhello>>> class A (object): @classmethod def SayHello (CLS): Print (' A.sayhello ') # definition Subclass B, inheriting A, overriding the class method SayHello, calling the SayHello method of the parent class >>> Class B (A): @classmethod def SayHello (CLS): Print (' B.say Hello ') Super (). SayHello () # defines subclass C, inherits B, overrides the class method SayHello, in which the SayHello method of calling the parent class >>> class C (B): @classmethod D EF SayHello (CLS): Print (' C.sayhello ') super (). SayHello () #调用C的类方法sayHello, which calls C's class method of the direct parent Class B SayHello, called when B's Sayhell The O method also calls the class method of the direct parent Class A of B sayhello>>> C.sayhello () c.sayhellob.sayhelloa.sayhello# redefine class C, the inheritance relationship is unchanged, use Super (C,C) The way to call the parent class method >>> class C (B): @classmethod def SayHello (CLS): Print (' C.sayhello ') Super (C,C). sayhe Llo () #调用C的类方法sayHello, super (C,C) proxy object, locate the direct parent Class B of C, and then call C's class method of the direct parent Class B SayHello, called when B's SayHello method calls B's direct parent Class A class method SayHello >>> C.sayhello () c.sayhellob.sayhelloa.sayhello# redefine Class C, inherit the same relationship, call the parent class method using Super (B,C) >>> Class C (B ): @classmethod def SayHello (CLS): Print (' C.sayheLlo ') Super (B,C). SayHello () #调用C的类方法sayHello, super (B,C) proxy object, locate the direct parent Class A of B, and then call the class method of the direct parent Class A of B SayHello, which does not call the SayHello method of B >>> C.sayhello () c.sayhelloa.sayhello# defines a new Class D, and A, B, C no inheritance Relationship >>> class D (object): @classmethod def Sayh Ello (CLS): Print (' D.sayhello ') #重新定义类C, inheritance is the same, call the parent class method using Super (D,C) >>> class C (B): @classmethod def S Ayhello (CLS): Print (' C.sayhello ') Super (D,C). SayHello () #调用C的类方法sayHello, super (D,C) proxy object, locate the direct parent class of Object B, and then convert C Into Class D, conversion failed call error >>> C.sayhello () c.sayhellotraceback (most recent called last): File "<pyshell#81>", Line 1, in & Lt;module> C.sayhello () File "<pyshell#80>", line 5, in SayHello Super (D,C). SayHello () typeerror:super (Typ E, obj): obj must is an instance or subtype of type

Python built-in function (--super)

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.