【发布时间】:2017-05-01 13:47:12
【问题描述】:
class Acct:
def __init__(self, deposit):
self.balance = deposit
def balance(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)
class ChkAcct(Acct):
def __init__(self, deposit):
super().__init__(deposit)
class SavAcct(Acct):
def __init__(self, deposit):
super().__init__(deposit)
savings_account_starting_balance = float(input("Enter a starting balance for your savings account :"))
savings_account = SavAcct(savings_account_starting_balance)
savings_account.balance()
checking_account_starting_balance = float(input("Enter a starting balance for your checking account :"))
checking_account = ChkAcct(checking_account_starting_balance)
checking_account.balance()
savings_account.getDeposit(float(input("Enter a deposit ammout for savings account :")))
checking_account.getDeposit(float(input("Enter a deposit ammout for checking account:")))
savings_account.getWithdraw(float(input("Enter a withdraw ammout from savings:")))
checking_account.getWithdraw(float(input("Enter a withdraw ammout from checking:")))
我需要创建 2 个类 ChkAcct 和 SavAcct。每个类都应该有一个balance 属性。每个类都应该有一个deposit 方法。每个类都应该有一个withdraw 方法。每个类还应该有一个transfer 方法,该方法调用自己的withdraw 方法并从其他类调用deposit 方法。
我似乎无法弄清楚如何制作传输方法。
【问题讨论】:
-
如果你想从一个账户取钱,然后放到另一个账户上,你应该使用instances。例如,
checking_acount.deposit(savings_account.withdraw(amount))。拥有一个针对特定其他类的方法实际上没有意义。 -
给该方法一个其他类的实例,并在其上调用withdraw/deposit方法。
-
正如@Carcigenicate 建议的那样,您将拥有例如
checking_account.transfer(amount, savings_account)。这意味着子类不必相互了解太多,只需它们共享Acct接口即可。
标签: python python-3.x subclass invoke subclassing