Python多重继承时属性的调用顺序

使用多重继承时,属性的解析会变得非常复杂,因为可以使用很多搜索路径来绑定属性。在查找使用了多重继承的属性时,会将所有基类按从“最特殊”的类型到“最不特殊”的类这种顺序进行排列。然后在搜索属性时,就会按这个顺序搜索,直至找到该属性的第一个定义。可通过类的__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'>)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值