This article and everyone to share is mainly in Python development , call the parent class two methods similarities and differences, I hope to learn from you and use the Python language is helpful.
There are two ways to call the parent class in Python: super (Child, Self). Method (args) and Parent.method ( Self, args) . I used one of these to report the following error:
I can't find them . Classobj . When I change the call to super (B, self), F (name) works correctly and the result is correct.
parsing errors
because the base class does not inherit Object , in python , one can be created like this:
class A:
Pass
You can also create this:
class A(object):
Pass
The difference between the two is:
This is the old class . ( former ) and new types ( latter ) the difference.
Python3 has removed the old type, meaning that it has implicitly inherited the object , so thePython3 does not write the inheritance Object there's no difference.
Two different types of calls
What is the difference between parent.__init__ (self) and super (Child, self). __init__ () ?
Super understands the parent class as well,Python actually refers to the next class in MRO!
Super actually did this , look at the answer :
def Super(CLS, inst):
MRO = Inst.__class__.mro () # Always the most derived class
return mro[mro.index (CLS) + 1]
MRO Full name Method Resolutionorder, which represents the order in which classes inherit.
Super is used to solve multiple inheritance problems , assuming B C D is directly inheriting class A
class E(B, C, D):
def __init__(self):
# code ...
if the Class E constructor uses super (E, self). __init__ () , The Class A constructor is executed once, and in another way,a The constructor of the class is executed multiple times.
in MRO , the base class always appears after the derived class, and if there are multiple base classes, the relative order of the base classes remains unchanged.
Source: Habitat later than one mound
Python calls the parent class method