继承,多继承
继承:一个类继承另外一个类的方法
class A(object): def my_print(self): print("Hello world!") class B(A): pass b = B() b.my_print()
A是父类,也叫基类,B叫子类,object叫顶级基类。可以通过__bases__特殊属性查看父类
多继承:一个类继承多个父类的方法
class A(object):
def __init__(self, name, age):
self.name = name
self.age = age
def first_print(self):
print("Hello world! My name is %s,I'm %s years old." % (self.name, self.age))
class B(A):
def __init__(self, name, age):
super().__init__(name, age) #super函数可以调用父类方法
def second_print(self):
print("Hello python! My name is %s,I'm %s years old." % (self.name, self.age))
class C(object):
def third_print(self):
print("Hello user! My name is %s,I'm %s years old." % (self.name, self.age))
class D(B, C):
def __init__(self, name, age):
B.__init__(self, name, age)
def fourth_print(self):
super().second_print() #调用父类方法
super().third_print()
print("Hello everybody! My name is %s,I'm %s years old." % (self.name, self.age))
b = B("Anni", 11)
d = D("Lucy", 12)
b.first_print()
d.first_print()
print(D.mro()) #查看继承顺序
print(D.__bases__) #查看所有父类
多继承最好只有一层,且是最后一层;一般情况下“Mix-in类”是继承的终点 !