MrJoe
MrJoe

Reputation: 445

Print all class instances stored in a list

I am trying to create a list of N instances of class Name and then call back a parameter of that instance. My code is below.

I get an error: Exception has occurred: AttributeError 'str' object has no attribute 'get_name'

and am not sure how to fix it. Any ideas? Thank you

class Name:
    global listName 
    listName = []

    def __init__(self,name):
        self.name = name
        listName.append (self.name)

    @property
    def get_name (self):
        print  (self.name)


for i in range (10):
    Name(f"Name{i}")

for i in range (10):
    listName[i].get_name

Upvotes: 0

Views: 469

Answers (2)

theblackips
theblackips

Reputation: 809

You did not append the instance of Name to your list, you only appended the name as a string.

See this line in the constructor of Name:

listName.append (self.name)

That line has to be

listName.append(self)

for your code to work.

Also:

As Patrick Artner pointed out in the comments, listName[i].get_name is not a function call. You have to add parentheses to call a function, like this:

listName[i].get_name()

Another thing:

As I just learned myself, you made listName a class variable by declaring it in the body of Name. You have to access it as Name.listName. The global listName statement is not needed.

Upvotes: 3

user11416843
user11416843

Reputation:

listName.append(self) is correct. get_name is worked instead of get_name().

class Name:
    global listName 
    listName = []

    def __init__(self,name):
        self.name = name
        listName.append (self)

    @property
    def get_name (self):
        print (self.name)

for i in range (10):
    Name(f"Name{i}")

for i in range (10):
    listName[i].get_name


Name0
Name1
Name2
Name3
Name4
Name5
Name6
Name7
Name8
Name9

Upvotes: 0

Related Questions