使用多重继承时,属性的解析会变得非常复杂,因为可以使用很多搜索路径来绑定属性。在查找使用了多重继承的属性时,会将所有基类按从“最特殊”的类型到“最不特殊”的类这种顺序进行排列。然后在搜索属性时,就会按这个顺序搜索,直至找到该属性的第一个定义。可通过类的__mro__属性查看其基类的顺序。
# coding=utf-8
#多重继承的属性查找顺序,由最特殊的类到最不特殊的类,由子类到基类,由左边基类到右边基类
class Account(object):
num_accounts=0 #类变量,所有成员共享
def __init__(self,name,balance):
self.name=name #实例属性
self.balance=balance
Account.num_accounts+=1
def __del__(self): #实例方法
Account.num_accounts-=1
def deposit(self,amt):
self.balance+=amt
def withdraw(self,amt):
self.balance-=amt
def inquiry(self):
return self.balance
class DepositCharge(object):
fee=5.00
def depoist_fee(self):
# self.withdraw(self.fee) 实例d的方法withdraw()会再调用基类的方法withdraw_fee()造成循环调用
# super(EvilAccount,self).withdraw(self.fee)
super(EvilAccount,self).withdraw(DepositCharge.fee)
class WithdrawCharge(object):
fee=2.50
def withdraw_fee(self):
# self.withdraw(self.fee) 实例d的方法withdraw()会再调用基类的方法withdraw_fee()造成循环调用
# super(EvilAccount,self).withdraw(self.fee)
super(EvilAccount,self).withdraw(WithdrawCharge.fee)
class EvilAccount(Account,DepositCharge,WithdrawCharge):
def deposit(self,amt):
self.depoist_fee()
super(EvilAccount,self).depoist(amt)
def withdraw(self,amt):
self.withdraw_fee()
super(EvilAccount,self).withdraw(amt)
d=EvilAccount("Dave",500) #创建EvilAccount实例d
#d.fee 为5.0 d的后2基类均有类变量fee,但DepositCharge基类在左边,取其值5.00
d.depoist_fee()
print(d.balance)
#495.0
d.withdraw_fee()
#292.5
print(d.balance)
print(EvilAccount.__mro__)
#(<class '__main__.EvilAccount'>, <class '__main__.Account'>, <class '__main__.DepositCharge'>, <class '__main__.WithdrawCharge'>, <class 'object'>)