【问题标题】:Manipulating items of array of class objects in Python在 Python 中操作类对象数组的项
【发布时间】: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


【解决方案1】:

有效:

for i in individualAccountList:
        print i.name

给予:

Casey
Bill
Eric
Tom

比:

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

【讨论】:

    猜你喜欢
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2011-01-31
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多