简体   繁体   中英

How to print all the instances in a class one by one?

How to print all the instances of a class one by one?

This is the code:

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)

Error is :

Traceback (most recent call last):
  File "ex1.py", line 23, in <module>
    print(n.age)
AttributeError: 'str' object has no attribute 'age'

As your error message suggests, you are trying to access an age attribute of a string object. This is because n is the loop variable that iterates over the list x .

This list consists of strings which you are getting confused with because they represent your variables' "names".

What you want to do is simply change your list to hold the actual variables and not their names as strings. Like so:

x = [a100, a300, a500, a200, a400]

您可以通过 globals() 获取它们 - 返回所有当前全局对象的映射,例如:

print([globals()[s].age for s in x])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM