有很多方法可以实现这一点。
这里有一个:class Acct:
def __init__(self, deposit):
self.balance = deposit
# Try to avoid same names for methods and properties, unless you have a good reason for it
# Otherwise you may end up with an error like this: "TypeError: 'float' object is not callable",
# when you try to call your original balance() method
# So I renamed it to getBalance()
def getBalance(self):
print("Your balance is $",self.balance)
def getDeposit(self, deposit):
self.balance = self.balance + deposit
print("Your new balance is $",self.balance)
def getWithdraw(self, withdraw):
self.balance = self.balance - withdraw
print("Your new balance is $",self.balance)
# Transfer 'amount' from current instance to 'destination' instance
def transfer(self, amount, destination):
self.getWithdraw(amount)
destination.getDeposit(amount)
class ChkAcct(Acct):
def __init__(self, deposit):
super().__init__(deposit)
class SavAcct(Acct):
def __init__(self, deposit):
super().__init__(deposit)
# Set up the accounts and fund them
print("1. Setting accounts")
savings_account = SavAcct(100.00)
checking_account = ChkAcct(200.00)
savings_account.getBalance()
checking_account.getBalance()
# Now do the transfer
print("2. Transferring money")
savings_account.transfer(50.00, checking_account)
输出如下:
^{pr2}$
另一种方法是为此提供一个独立的函数:def transfer(amount, origin, destination):
origin.getWithdraw(amount)
destination.getDeposit(amount)
然后叫它:transfer(50.00, savings_account, checking_account)