【问题标题】:Print a list from my class (python)从我的班级打印一个列表(python)
【发布时间】:2017-09-17 07:11:29
【问题描述】:

我有一个关于客户信息的课程。所有数据元素之一是self.history,如果我将每个客户的历史记录保存在列表中。如果我将名称保存为键,将其他信息保存为值,则每个客户也在类之外的字典中。我的问题是如何为每个客户打印此列表。

我试过了:

class Customer:
    def __init__(self, name, car, reg):
        self.name = name
        self.car = car
        self.reg = reg
        self.history = []


def add_new_customer:
    account = dict()
    name = input("Name: ")
    car = input("Car: ")
    reg = input("Regnummber : ")
    account[name] = Customer(name, car, reg)


def print_all_accounts():
    for keys in account:
        print(keys.history)

代码更大,我做了很多事情,比如 name.history.append() 等等(500 行)。但这是行不通的事情。

我得到错误:

AttributeError: 'str' object has no attribute 'history'

【问题讨论】:

    标签: python list class dictionary


    【解决方案1】:

    您只是在遍历字典键。

    for keys in account:
        print(account[keys].history)
    

    甚至更好:

    for key, value in account.items():
        print(value.history)
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多