我最近学过Python。我无法在此代码中捕获错误。有什么问题?
class BankAccount:
def __init__(self, initial_balance):
"""Creates an account with the given balance."""
self = [initial_balance, 0]
def deposit(self, amount):
"""Deposits the amount into the account."""
self += amount
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.
"""
self[0] -= amount
if self[0] < 0:
self[0] -= 5
self[1] += 1
def get_balance(self):
"""Returns the current balance in the account."""
return self[0]
def get_fees(self):
"""Returns the total fees ever deducted from the account."""
return 5*self[1]
my_account = BankAccount(10)
my_account.withdraw(15)
my_account.deposit(20)
my_account.get_balance(), my_account.get_fees()
错误是:
Traceback (most recent call last):
File "C:\Python34\bank.py", line 28, in <module>
my_account.withdraw(15)
File "C:\Python34\bank.py", line 15, in withdraw
self[0] -= amount + 5
TypeError: 'BankAccount' object does not support indexing
self
值包含initial_balance
以及已提取的提款次数。
答案 0 :(得分:3)
self总是指调用类函数的对象。因此,建议不要为自变量分配一些内容,如:
self = #something
在构造函数中。为该变量命名。像:
self.details = [initialbalance,0]
并在任何地方使用变量名称。
答案 1 :(得分:0)
看起来应该是这样的:
class BankAccount:
OVERDRAW_PENALTY = 5
def __init__(self, opening_balance=0):
self.balance = opening_balance
self.withdrawals = 0
def withdraw(self, amount):
self.withdrawals += 1
self.balance -= amount
if self.balance < 0:
self.balance -= self.OVERDRAW_PENALTY
return amount
请注意,我使用self
来访问实例和类属性,而不是尝试直接分配给它。另外,我已经考虑了#34;魔术数字&#34; 5
,所以发生的事情更清楚。
此外,您get_fees
的实施方式不正确 - 无论是否收取费用,提款的数量目前都会增加。您应该单独存储self.overdrawn_withdrawals
计数,或保留一个正在运行的self.fees
属性。
最后,我已将return amount
添加到withdraw
的末尾 - 这可以让您执行以下操作:
account2.deposit(account1.withdraw(100))
轻松在BankAccount
之间转账。
答案 2 :(得分:0)
self
指的是BankAccount对象。您需要分配和引用实例变量。
您的__init__()
方法应该是这样的:
class BankAccount:
def __init__(self, initial_balance):
"""Creates an account with the given balance."""
self.balance = initial_balance
self.fees = 0
self.withdrawals = 0
def deposit(self, amount):
"""Deposits the amount into the account."""
self.balance += amount
同样,withdraw()
和get_balance()
应引用self.balance
,get_fees()
应引用self.fees
。