pythonrenpy

Using for loop variable on a getattr() function


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?


Solution

  • 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)