A
A
anton_zaboev2021-12-13 18:22:30
Python
anton_zaboev, 2021-12-13 18:22:30

How to loop through and add to the list all instances of a class?

Good evening everyone! Can you please tell me how to iterate and add to the list all instances of the class?
here is the code

class Hero(object):
    # heroes = []
    def go_right(self):
        print("Я иду направо")

    def go_left(self):
        print("Я иду налево")

    def observe(self):
        print("Я осматриваюсь")

    def __init__(self):
        super().__init__()


pythomir = Hero()
flaskomir = Hero()
djangomir = Hero()

heroes = []

for item in Hero:
    heroes.append(item)
print(heroes)

assert len(heroes) == 3, "в списке не три героя"
assert isinstance(pythomir, Hero) , "pythomir – не экземпляр Hero"
assert isinstance(flaskomir, Hero) , "flaskomir – не экземпляр Hero"
assert isinstance(djangomir, Hero) , "djangomir – не экземпляр Hero"


At the moment I solved the problem like this
heroes.append(pythomir)
heroes.append(flaskomir)
heroes.append(djangomir)

But I would like to know how it can be done better.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-12-13
@anton_zaboev

No way, your solution with three .append() is correct.
If, when creating an instance of a class, it does not register itself in some list or other collection, then it will not be possible to learn about it from another part of the program.
And if it does, it will require a damn non-obvious hack, which is better not to use.

D
Dmitry Shitskov, 2021-12-13
@Zarom

As an option

class Hero(object):
    heroes = []
    
    def go_right(self):
        print("Я иду направо")

    def go_left(self):
        print("Я иду налево")

    def observe(self):
        print("Я осматриваюсь")

    def __init__(self):
        super().__init__()
        Hero.heroes.append(self)
        
    def __del__(self):
        Hero.heroes.remove(self)

pythomir = Hero()
flaskomir = Hero()
djangomir = Hero()

heroes = Hero.heroes

assert len(heroes) == 3, "в списке не три героя"
assert isinstance(pythomir, Hero) , "pythomir – не экземпляр Hero"
assert isinstance(flaskomir, Hero) , "flaskomir – не экземпляр Hero"
assert isinstance(djangomir, Hero) , "djangomir – не экземпляр Hero"

PS Pythonists, come and throw hats if something goes wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question