在Python中操作类对象数组的项

时间:2015-05-18 22:26:42

标签: python arrays loops dictionary

对于下面的代码,我使用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()

1 个答案:

答案 0 :(得分:1)

它有效:

for i in individualAccountList:
        print i.name

给出:

Casey
Bill
Eric
Tom

比:

individualAccountList[0].name = "name changed"
print individualAccountList[0].name
>> name changed