Answer the question
In order to leave comments, you need to log in
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"
heroes.append(pythomir)
heroes.append(flaskomir)
heroes.append(djangomir)
Answer the question
In order to leave comments, you need to log in
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.
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"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question