When it comes to super, you may find it very simple, not the way to invoke the parent class. If it is so simple, it will not have this article, and listen to me carefully. convention Before we begin, let's make a pact about the Python version used in this article. The default is Python 3, which means that the classes defined in this article are new classes. If you use Python 2, remember to inherit object:
# default, Python 3
Class A:
pass
# python 2
Class A (object):
Pass
Another difference between Python 3 and Python 2 is that Python 3 can use the direct use of super (). XXX instead of super (Class, self). XXX:
# By default, Python 3
Class B (a):
def add (self, x):
super (). Add (x)
# Python 2
Class B (a):
def add (self, x):
super (B, self). Add (x)
So if you're using Python 2, remember to replace super () with Suepr (Class, self) in this article.
If there are other situations that are not compatible with Python 2, I will mention them in the text. Single Inheritance
In single inheritance, super is basically the method used to invoke the parent class, as you would expect.
Class A:
def __init__ (self):
SELF.N = 2
def add (self, m):
print (' Self is {0} @a.add '. Format (self))
SELF.N + M
class B (A):
def __init__ (self):
SELF.N = 3
def add (self, m):
print (' Self is {0} @b.add '. f Ormat (self))
super (). Add (m)
SELF.N + + 3
What do you think is the value of the B.N after executing the following code?
b = B ()
B.add (2)
print (B.N)
The results of the implementation are as follows:
Self is <__main__. B object at 0x106c49b38> @b.add the
self is <__main__. B object at 0x106c49b38> @a.add
8
This result illustrates two questions: 1, Super (). Add (m) did call the Add method of parent class A. 2. When super (). Add (M) invokes the parent class method def add (self, m), self is not an instance of the parent class but an instance of a subclass in the parent class, so the result after B.add (2) is 5 instead of 4.
I don't know if the result is the same as you think. Let's look at an example of multiple inheritance here. Multiple Inheritance
This time we define a class C, a class D:
Class C (A):
def __init__ (self):