python - 从我的类(class)打印列表(python)

标签 python list class dictionary

我有一个包含客户信息的类(class)。所有数据元素之一是 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'

最佳答案

您只是循环遍历字典键。

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

或者更好:

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

关于python - 从我的类(class)打印列表(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523114/

相关文章:

python - 在 Python 3 中使用 XPath 解析 XML

python - 从列表中获取相对于 python 中另一个元素的元素

java - 如何获取类名并使用它?

c++ - 为什么在一个类中使用 uint64_t 需要比 2 个 uint32_t 更多的内存?以及如何防止这种情况?

python - Sklearn 模型 (Python) 与 NodeJS (Express) : how to connect both?

python - 如何查找 ImageDataGenerator 生成的图像数量

python - Python 中的 Anagram 检查

Python - 迭代并提取字典类型列表的元素

python - 在字符之间查找多个字符串

java - 获取真实的类类型