前のセクションでは、親クラスのメソッドを書き直しましたが、これら2つの親クラスのメソッドを引き続き使用する場合は、次のように書き直すことができます。
class Gun1(object):
def __init__(self):
self.length = 100
def shoot(self):
print('bang1')
class Gun2(object):
def __init__(self):
self.length = 200
def shoot(self):
print('bang2')
class Wuzi(Gun1,Gun2):
def shoot(self):
# 注意这里要先初始化自己,这样可以避免调用父类方法后再调用自己的方法时,还是父类的方法输出
self.__init__()
print('bang3')
def shoot1(self):
# 调用父类方法时先初始化父类
Gun1.__init__(self)
Gun1.shoot(self)
def shoot2(self):
# 同上
Gun2.__init__(self)
Gun2.shoot(self)
wuzi = Wuzi()
wuzi.shoot()
wuzi.shoot1()
wuzi.shoot2()
このときの出力はbang3、bang1、bang2です。
複数の継承
class Gun1(object):
def __init__(self):
self.length = 100
def shoot(self):
print('bang1')
class Gun2(object):
def __init__(self):
self.length = 200
def shoot(self):
print('bang2')
class Wuzi(Gun1,Gun2):
def shoot(self):
# 注意这里要先初始化自己,这样可以避免调用父类方法后再调用自己的方法时,还是父类的方法输出
self.__init__()
print('bang3')
def shoot1(self):
# 调用父类方法时先初始化父类
Gun1.__init__(self)
Gun1.shoot(self)
def shoot2(self):
# 同上
Gun2.__init__(self)
Gun2.shoot(self)
class XiaoWuzi(Wuzi):
pass
wuzi = XiaoWuzi()
wuzi.shoot()
wuzi.shoot1()
wuzi.shoot2()
XiaoWuziのようなWuzi(2つの親クラスから継承)を継承する形式は、マルチレイヤー継承と呼ばれ、最上位の親クラス(Gun1、Gun2)のメソッドを引き続き使用できます。