Usage of super () and _ class _ in Python3, and python3 _ class _
The subclass accesses the attributes of the parent class with the same name, but does not want to directly reference the name of the parent class, because it may be modified at any time, so the data is retained only one copy. In fact, there is a better reason not to directly reference the name of the parent class. For details, see Python's super () considered super! | Deep Thoughts by Raymond Hettinger.
At this time, super () will be available --
Copy codeThe Code is as follows:
Class:
Def m (self ):
Print ('A ')
Class B ():
Def m (self ):
Print ('B ')
Super (). m ()
B (). m ()
Of course, super () in Python 2 must be a parameter, so you have to write it like this:
Copy codeThe Code is as follows:
Class B ():
Def m (self ):
Print ('B ')
Super (B, self). m ()
You need to mention your own name. This name is also dynamically searched. In this case, replacing the class in the third-party library will cause problems.
Super () solves the problem of accessing methods in the parent class. So what if you want to access the attributes of the parent class (accurately speaking, it is the third class in the method Resolution Sequence (MRO?
For example, Class B inherits from Class A and overwrites the m method of Class. Now we need A class C, which requires some methods of Class B, but instead of m methods of Class B, we should use A instead. How can I indirectly reference the m METHOD OF? You cannot use self. _ class _ because C may be further inherited.
I noticed from the document that, super is implemented by inserting a name named _ class _ (super searches for the name of _ class _ from the call stack ). As mentioned in the document, you can directly access the _ class _ name when defining a method, which is always the class defined by the method. Continue with our single-letter class:
Copy codeThe Code is as follows:
Class C (B ):
Def m (self ):
Print ('C ')
# See 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 ()
You will get:
Copy codeThe Code is 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.