我有一个包含客户信息的类(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/