我想让这个程序在不使用全局变量的情况下运行。基本上,如果此人退出并最终以负数结束,他们将被处以5英镑的罚款。每笔交易如果是负的,也会被罚5英镑。
假设只有两个帐户,这个程序似乎运行良好:
account1 = Bankaccount(20)
account2 = Bankaccount(5)
但这是它的局限性。如何允许无限帐户?所以我不必拘泥于两个全球性的。我希望这是有意义的,假设我必须改变取款功能并获得费用,但我是新的面向对象编程,所以我卡住了。谢谢你的帮助!
pen = 0
pen2 = 0
class BankAccount:
def __init__(self, initial_balance):
"""Creates an account with the given balance."""
self.money = initial_balance
def deposit(self, amount):
"""Deposits the amount into the account."""
self.money += amount
return self.money
def withdraw(self, amount):
"""
Withdraws the amount from the account. Each withdrawal resulting in a
negative balance also deducts a penalty fee of 5 dollars from the balance.
"""
global pen, pen2
penalty = 5
if self.money - amount < 0:
self.money -= (amount + penalty)
if self == account1:
pen += 5
elif self == account2:
pen2 += 5
else:
self.money -= amount
return self.money
def get_balance(self):
"""Returns the current balance in the account."""
return self.money
def get_fees(self):
"""Returns the total fees ever deducted from the account."""
global pen, pen2
if self == account1:
return pen
elif self == account2:
return pen2
将惩罚设置为实例属性,就像
money
是:后来:
只需将全局变量转换为实例变量:
我还注意到您在
withdraw
函数中声明了一个名为penalty
的变量。这看起来是避免magic numbers的良好实践的开始,因此我继续沿着这些思路,将其作为BankAccount
类的常量属性。另外,在Python中,我们通常不使用函数来访问属性。与其
bobs_account.get_fees()
,不如bobs_account.penalty
更正常。惩罚还应该是
BankAccount
对象的实例变量:相关问题 更多 >
编程相关推荐