Is it Pythonic to have a class keep track of its instances?
- by Lightbreeze
Take the following code snippet
class Missile:
instances = []
def __init__(self):
Missile.instances.append(self)
Now take the code:
class Hero():
...
def fire(self):
Missile()
When the hero fires, a missile needs to be created and appended to the main list. Thus the hero object needs to reference the list when it fires. Here are a few solutions, although I'm sure there are others:
Make the list a global,
Use a class variable (as above), or
Have the hero object hold a reference to the list.
I didn't post this on gamedev because my question is actually more general: Is the previous code considered okay? Given a situation like this, is there a more Pythonic solution?