super keyword application lass Animal: # Animal def __init__(self, name , aggr , hp ): # Double down method built-in for method dynamic properties self.name = name # object attribute instance attribute self.aggr = aggr self.hp = hp def eat(self): print('in Animal eat') class Person(Animal): # 类名 Person def __init__(self,name,sex,aggr,hp): self.sex = sex # derived properties # Animal.__init__(self,name,aggr,hp) super().__init__(name,aggr,hp) # In single inheritance super will look for the parent class # And when using super to call the parent class method, you don't need to pass the self parameter again def eat(self): print('in Person eat') Animal.eat(self) #alex.eat()=Person.eat(alex) # super().eat() alex = Person('alex','unknown',1,250) print(alex.__dict__) # Animal.eat(alex) # super(Person,alex).eat()
Notice:
The first one to note:
Animal.eat(self) and super().eat() in person class def eat() drink directly
So the parentheses after super in super().eat() can be omitted
And if we call it outside, the parentheses cannot be omitted directly (super(Person,alex).eat())
The second one to note:
alex.eat()=Person.eat(alex) * object.methodname()=classname.eat(object)
Two: Single Inheritance Exercises
class A: def wahaha(self):print('in A') class B(A): def wahaha(self):print('in B') class C(B): def wahaha(self):print('in C') class D(C):pass # def wahaha(self):print('in D') d = D() d.wahaha() # Don't happen circular inheritance # Dependency Inversion Principle: # High-level modules should not depend on low-level modules
Notice:
1 If the subclass attribute is called, the subclass does not find the parent class, and so on, constantly looking for the parent class.
2 Cyclic inheritance cannot occur
3 Dependency inversion principle, high-level modules (D is the innermost layer) should not depend on low-level modules (A outermost layer)
simple multiple inheritance
class A:pass # def qqxing(self): # print('in A') class B: def qqxing(self): print('in B') class C: def qqxing(self): print('in C') class D(B,A,C): pass # def qqxing(self): # print('in D') d = D() d.qqxing()
Search according to D(B,A,C) according to BAC order, if a Pass appears, look up
Note: All classes in Python 3 inherit object
New-style classes: a class inherits object
Classic class: a class does not inherit object
Classic classes do not have mro methods, new-style classes have
Python3 only has super
The notes are as follows: