Subclass to access the same name as the parent class, and you don't want to refer directly to the parent class's name, because you might be able to modify it, so the data remains just one copy. In fact, there are better reasons not to refer directly to the name of the parent class, see Python ' s Super () considered super! | Deep thoughts by Raymond Hettinger.
It's time for super ()
Copy Code code as follows:
Class A:
def m (self):
Print (' A ')
Class B (A):
def m (self):
Print (' B ')
Super (). m ()
B (). m ()
Of course Python 2 super () must be parametric, so write this:
Copy Code code as follows:
Class B (A):
def m (self):
Print (' B ')
Super (B, self). m ()
Need to mention your name. This name is also dynamically searched, in which case replacing classes in a Third-party library can be problematic.
Super () solves the problem of accessing methods in the parent class well. So what about accessing the parent class of the parent class (exactly, the class in the third in the method parsing order (MRO))?
For example, class B is inherited a, and it rewrites the M method of a. Now we need a class C, which requires some methods of class B, but not the M method of B, but instead a. How do I refer indirectly to the M method of a? The use of self.__class__ is certainly not possible, as C may also be further inherited.
I noticed from the document that the implementation of super was implemented by inserting a name named __class__ (Super would look up the __class__ name from the call stack). So, as implied in the document, you can actually access the __class__ name directly when you define the method, which is always the class defined by the method. Continue with our single letter class:
Copy Code code as follows:
Class C (B):
def m (self):
Print (' C ')
# The difference!
Print (__class__.__mro__)
Print (self.__class__.__mro__)
__CLASS__.__MRO__[2].M (self)
Class D (C):
def m (self):
Print (' D ')
Super (). m ()
o = D ()
O.M ()
Will get:
Copy Code code as follows:
D
C
(<class ' t.c ', <class ' t.b ', <class ' t.a ', <class ' object ' >)
(<class ' t.d ', <class ' t.c ', <class ' t.b ', <class ' t.a ', <class ' object ' >)
A
However, PyPy does not support the __class__ name.