Is it Pythonic to have a class keep track of its instances?
Posted
by
Lightbreeze
on Stack Overflow
See other posts from Stack Overflow
or by Lightbreeze
Published on 2012-03-30T09:29:01Z
Indexed on
2012/03/30
11:29 UTC
Read the original article
Hit count: 361
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?
© Stack Overflow or respective owner