1、深度优先
#!/usr/bin/env python
class Account:
"""bank account"""
def __init__(self, holder):
self.balance = 0
self.holder = holder
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return 'not enough money!'
return self.balance - amount
class RemoteAccount(Account):
"""docstring for RemoteAccount"""
deposit_charge = 1
def __init__(self, holder):
super(RemoteAccount, self).__init__(holder)
def deposit(self, amount):
return Account.deposit(self, amount - self.deposit_charge)
class InterbankAccount(Account):
"""docstring for InterbankAccount"""
withdraw_charge = 1
def __init__(self, holder):
super(InterbankAccount, self).__init__(holder)
def withdraw(self, amount):
return Account.withdraw(self, amount + self.withdraw_charge)
class RemoteInterbankAccount(RemoteAccount, InterbankAccount):
"""docstring for RemoteInterbankAccount"""
def __init__(self, holder):
self.holder = holder
self.balance = 0
account = RemoteInterbankAccount('zhang3')
#print [c.__name__ for c in RemoteInterbankAccount.mro()]
print account.deposit(12)
#>>> 11
print account.withdraw(10)
#>>> 1
2、广度优先
#!/usr/bin/env python
class Account(object):
"""bank account"""
def __init__(self, holder):
self.balance = 0
self.holder = holder
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return 'not enough money!'
return self.balance - amount
class RemoteAccount(Account):
"""docstring for RemoteAccount"""
deposit_charge = 1
def __init__(self, holder):
super(RemoteAccount, self).__init__(holder)
def deposit(self, amount):
return Account.deposit(self, amount - self.deposit_charge)
class InterbankAccount(Account):
"""docstring for InterbankAccount"""
withdraw_charge = 1
def __init__(self, holder):
super(InterbankAccount, self).__init__(holder)
def withdraw(self, amount):
return Account.withdraw(self, amount + self.withdraw_charge)
class RemoteInterbankAccount(RemoteAccount, InterbankAccount):
"""docstring for RemoteInterbankAccount"""
def __init__(self, holder):
self.holder = holder
self.balance = 0
account = RemoteInterbankAccount('zhang3')
print [c.__name__ for c in RemoteInterbankAccount.mro()]
#>>> ['RemoteInterbankAccount', 'RemoteAccount', 'InterbankAccount', 'Account', 'object']
print account.deposit(12)
#>>> 11
print account.withdraw(10)
#>>> 0
我们通常称深度优先为classic,广度优先为new-style——基类需继承object。广度优先基于C3 Method Resolution Ordering方法,该方法对应于Python中的mro方法。多重继承是一个无法标准化的问题,每一种提供多重继承的语言都有自己的继承方式,我们只需遵循这种特定方式就可以了。