Three characteristics of the target for two: Inheritance (Inheritance)
Python also supports class inheritance, if a language does not support inheritance, the class has little meaning.
1.0.1 inherited wording
class Grandfather: def dance(self): pass class Father (Grandfather): # parent or base class def football(self): pass def basketball(self): pass def somking(self): pass def drinking(self): pass def haircare(self): pass class Son (Father): # subclasses, or derived class DEF Reading (Self): Pass obj = Son() obj.football()
The most simple exercises:
class F: def f1(self): print('F.f1') def f2(self): print('F.f2') class S(F): def s1(self): print('S.s1') obj = S() obj.s1() obj.f2()
1.0.2 Inheritance rewrite:
If the method with the parent class inside do not want to be the parent class inside the method, a re-write.
When executed, it will not go to the parent class method.
class F: def f1(self): print('F.f1') def f2(self): print('F.f2') class S (F.): DEF S1 (Self): Print ( ' S.s1 ' ) DEF F2 (Self): # parent class method overrides Print ( ' S.f2 ' ) obj = S() obj.s1 () # s1 is in the self parameter, this means that the era of obj obj.f2 () # self always refers to a caller invokes a method, is obj
If we want to execute the parent class's method, there are two methods: one is the super (), is a direct parent class name calling method
super () function is a method call the parent class (superclass) is used.
super is used to solve the problem of multiple inheritance, class name with no problem call the parent class method directly when using single inheritance, but if you use multiple inheritance, involves the search order (MRO), repeated calls (diamond inheritance) and various other problem.
MRO is the way class resolution order table, in fact, is the inheritance order table when the parent class method.
super syntax:
super(type[, object-or-type])
type: subclass name
bject-or-type: it is self
class F: def f1(self): print('F.f1') def f2(self): print('F.f2') class S(F): def s1(self): print('S.s1') def f2(self): Super (S, Self) .f2 () # find a parent class, then the parent class method performed f2 F.f2 (Self) # may be performed such parent class is rewritten Print ( ' S.f2 ' )
super().xxx;super(child,self).xxx
Method Method 1: super (subclass, self) in the parent class (arg).
Method 2 Method: The method of the parent class name of the parent class (. Self arg)
class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild (FooParent): DEF __init__ (Self): # Super (FooChild, Self) first find FooChild parent class (that class FooParent), then converts class FooChild object to object class FooParent of super (FooChild, self). the __init__ () Print ( ' Child ' ) def bar(self,message): super(FooChild, self).bar(message) print ('Child bar fuction') print (self.parent) if __name__ == '__main__': fooChild = FooChild() fooChild.bar('HelloWorld')