Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

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'

1 Answer

0 votes
by (25.1k points)

The problem in in your code's last third line. You've put:

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

When you should've put

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

This is becuse "a100" is string so it has not attribute called age while class instance a100 does

Related questions

Browse Categories

...