【发布时间】:2015-05-18 22:26:41
【问题描述】:
对于下面的代码,我使用 for 循环创建了一个类对象数组。但是,我无法访问和修改列表中的对象。我必须进行哪些更改才能完成这项工作?
def main():
class BankAccount:
def __init__(self,nameOfCustomer,balanceOfCustomer):
self.name = nameOfCustomer
self.balance = balanceOfCustomer
print "\nNew customer created in system with name " + self.name + " and initial balance of $" + str(self.balance)
def get_balance(self):
print "The current balance for " + self.name + " is: $" + str(self.balance)
return self.balance
def deposit(self,amount):
self.balance += amount
print self.name + " just deposited $" + str(amount)
return self.balance
def withdraw(self,amount):
self.balance -= amount
print self.name + " just withdrew $" + str(amount)
return self.balance
customerList = {"Eric": 10000,
"Tom": 20000,
"Bill": 25000,
"Casey": 40000}
individualAccountList = []
for key, value in customerList.iteritems():
individualAccountList.append(BankAccount(key,customerList[key]))
for i in individualAccountList:
print i
if __name__ == '__main__':
main()
【问题讨论】:
-
“但是,我无法访问和修改列表中的对象” -- 你能详细说明一下这句话吗?你想做什么?您当前的代码以何种方式失败?你期望你当前的代码做什么,它没有做什么?等
-
作为风格问题,
BankAccount类不应定义在main()中,而应在模块范围内。
标签: python arrays loops dictionary