类的继承
1.单继承
子类调用父类的一个方法,可以用super() 或super(PersonB,self).__init__(name, age)
也可以使用PersonA.__init__(self, name, age)来确保父类被正确的初始化
class PersonA: def __init__(self,name, age): self.name = name self.age = age print('init action in father class PersonA') def print_a(self): print("Name : ", self.name, ", Age: ", self.age) class PersonB(PersonA): def __init__(self, name, age,genger): super().__init__(name, age) #super(PersonB,self).__init__(name, age) #PersonA.__init__(self, name, age) #self.name = name #self.age = age self.genger=genger print('init action in father class PersonB') def print_x(self): print("Name : ", self.name, ", Age: ", self.age, ", genger: ", self.genger) a=PersonA('AAA',23) a.print_a() b=PersonB('BBB',24,'male') b.print_x()
2.多继承
class A(object): def __init__(self): print("Enter A") class B(A): def __init__(self): print('Enter B(A)') super(B,self).__init__() print('Leave B(A)') class C(A): def __init__(self): print('Enter C(A)') super(C, self).__init__() print('Leave C(A)') class D(B,C): def __init__(self): print('Enter D(B,C)') super(D,self).__init__() print("Leave D(B,C)") d=D()