单继承
class Father():
def __init__(self):
print("父类__init__")
self.a = 1
class Son(Father):
def __init__(self):
print("子类__init__")
self.b = 2
def show_son(self):
print(self.a, self.b)
if __name__ == "__main__":
son = Son()
son.show_son()
输出:
子类__init__
AttributeError: ‘Son’ object has no attribute ‘a’
原因:
子类Son的__init__覆盖了父类Father的__init__导致没有属性a
修改1:
class Father():
def __init__(self):
print("父类__init__")
self.a = 1
class Son(Father):
def __init__(self):
# 方法一
# Father.__init__(self) # 注意这里的self为Son的实例对象
# 方法二
super().__init__() # 不需要传self
print("子类__init__")
self.b = 2
def show_son(self):
print(self.a, self.b)
if __name__ == "__main__":
son = Son()
son.show_son()
输出:
父类__init__
子类__init__
1 2
多继承
class Father():
def __init__(self):
print("父类Father__init__")
self.father = 'father'
class Monther():
def __init__(self):
print("父类Monther__init__")
self.monther = 'monther'
class Son(Father, Monther):
def __init__(self):
Father.__init__(self) # 注意这里的self为Son的实例对象
Monther.__init__(self) # 注意这里的self为Son的实例对象
print("子类__init__")
self.son = 'son'
def show_son(self):
print(self.father, self.monther, self.son)
if __name__ == "__main__":
son = Son()
son.show_son()
输出:
父类Father__init__
父类Monther__init__
子类__init__
father monther son
class Father():
def __init__(self, father):
print("父类Father__init__")
self.father = father
class Monther():
def __init__(self, monther):
print("父类Monther__init__")
self.monther = monther
class Son(Father, Monther):
def __init__(self, father, monther, son):
Father.__init__(self, father) # 注意这里的self为Son的实例对象
Monther.__init__(self, monther) # 注意这里的self为Son的实例对象
print("子类__init__")
self.son = son
def show_son(self):
print(self.father, self.monther, self.son)
if __name__ == "__main__":
son = Son("father", "monther", "son")
son.show_son()
输出:
父类Father__init__
父类Monther__init__
子类__init__
father monther son