1 Inheritance:2 #The Python2 Classic class is inherited by depth first, and the new class is inherited by breadth first .3 #Python3 Classic Classes and new classes are inherited by breadth first.4 5 6 7 #Classic Class: class people:8 classPeople (object):#This is a new class, and it's changed when it comes to inheritance.9 Ten def __init__(self, Name, age): OneSelf.name =name ASelf.age = Age - - the defEat (self): - Print("%s is eating"%self.name) - - + defTalk (self): - Print("%s is talking"%self.name) + A defSleep (self): at Print("%s is sleeping"%self.name) - - #demonstration of multiple inheritance - classRelation (object): - defmake_friends (self, obj): - Print("%s is making friends with%s"%(Self.name, obj.name)) inSelf.friends.append (obj)#use obj to connect to another instance - to #Subclass Inheritance + classMan (People, Relation):#Be sure to have the parent class name in the parentheses, such as people - the def __init__(Self, name, age, sex="Mans"): * #people (). __init__ (Self,name, age) The first method of initialization $Super ().__init__(name, age)#Superclass,super function directly inherits all, Super (man, self) ellipsisPanax NotoginsengSelf.sex =Sex -Self.friends = [] the + defWorking_hard (self): A Print("earning money.") the + defSleep (self):#Refactoring the methods of the parent class - people.sleep (self) $ Print("mans%s is sleeping"%self.name) $ - - classWoman (People, Relation): the - def __init__(Self,name, age, Sex ="woman"):WuyiSuper ().__init__(name, age) theSelf.sex =Sex -Self.friends = [] Wu - defGet_birth (self): About Print("%s is giving birth to a baby."%self.name) $ - -P1 = People ("Adam", 26) - p1.eat () A Print("%s is%s years old."%(P1.name, p1.age)) + P1.sleep () the -M1 = Man ("Alex", 28) $ m1.eat () the M1.working_hard () the M1.sleep () the m1.make_friends (p1) the Print(M1.friends[0].name) - inW1 = Woman ("Shell", 27) the W1.get_birth () theW1.sleep ()
Python learning-Inheritance of classes