如何逐一打印类的所有实例?
这是代码:
class Person:
def __init__(self, fname, lname, age, gender):
self.fname = fname
self.lname = lname
self.age = age
self.gender = gender
class Children(Person):
def __init__(self, fname, lname, age, gender, friends):
super().__init__(fname, lname, age, gender)
self.friends = friends
a100 = Children("a1", "a10", 17, "male", "a2 , a3 , a4 , a5")
a200 = Children("a2", "a20", 17, "male", "a5, a1, a4, a3 ")
a300 = Children("a3", "a30", 17 , "male", "a2, a1")
a400 = Children("a4", "a40", 17, "female", "a1, a2")
a500 = Children("a5", "a50", 16, "male", "a2, a1")
x = ["a100", "a300", "a500", "a200", "a400"]
for n in x:
print(n.age)
错误是:
Traceback (most recent call last):
File "ex1.py", line 23, in <module>
print(n.age)
AttributeError: 'str' object has no attribute 'age'
答案 0 :(得分:1)
如错误消息所提示,您正在尝试访问字符串对象的age
属性。这是因为n
是循环访问列表x
的循环变量。
此列表包含一些令人困惑的字符串,因为它们代表了变量的“名称”。
您想要做的就是简单地更改列表以保留 actual 变量,而不是它们的名称作为字符串。像这样:
x = [a100, a300, a500, a200, a400]
答案 1 :(得分:0)
您可以通过globals()获得它们-返回当前所有全局对象的映射,如:
print([globals()[s].age for s in x])