Using for loop variable on a getattr() function

Question:

I have a class Person with the attributes name and level

class Person:

    def __init__(self, name, level):
            
        self.name = name
        self.level = level

let’s say i have a bunch of objects from that class with different attributes

p1 = Person("person1", "5")
p2 = Person("person2", "10")
p3 = Person("person2", "15")

And a list containing the name of all those objects

people_list = ["p1","p2","p3"]

i want to make a function on the Person class, that finds and prints all the levels
This is what i made so far.

def lvlFinder(self, people_list):
        
        for x, item in enumerate(people_list):
            y = getattr(p1, "level")
            print(y)

Is there a way so instead of p1 in getattr(p1,"level") i could have a variable that changes to p2 and so on as it loops.
I tried many different ways, but honestly i don’t even know if anything is right.
Is there a better way of doing this?

Asked By: v1sor1

||

Answers:

You have a few faults, each of which is obscuring other parts of the program.

Start by making a list of the people:

people_list = [p1, p2, p3]

Then you can iterate directly over the list:

def lvlFinder(people_list):
        for item in people_list:
            y = item.level
            print(y)

Finally you just have to call the function:

lvlFinder(people_list)
Answered By: quamrana

Your people_list variable should contain the Person objects instead of strings. Then you can loop over the list and get the levels like this:

people_list = [p1, p2, p3]

for person in people_list:
    print(person.level)

getattr() really is not needed or useful in this case.

Answered By: user99999
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.