I'm creating a little game which has multiple weapons. Each weapon is an object variable in the class 'Weapon'. I want to create an array which has every single Weapon object in it as its variable name. Is there an easy way of doing this or do I have to type each object name into the list myself? To clarify, I don't want to list the attributes of an object, I want something that returns a list of objects belonging to a given class.
Asked
Active
Viewed 430 times
0
-
2Why would you want an array of variable names? – Scott Hunter Jul 18 '19 at 18:53
-
Possible duplicate of [List attributes of an object](https://stackoverflow.com/questions/2675028/list-attributes-of-an-object) – roganjosh Jul 18 '19 at 18:54
-
So that I can iterate through it and print off specific attributes of each object. – Freddie Herriott Jul 18 '19 at 19:00
-
You can use this using `dir`, `__dict__` (if your class doesn't use `__slots__`), a well-placed `locals` call, or using metaclasses. – 0xdd Jul 18 '19 at 19:02
-
You should use one of the structures in the [weakref](https://docs.python.org/3/library/weakref.html) module. So you don't have to take care of removing. Just make the objects add themself in their `__init__()`. – Klaus D. Jul 18 '19 at 19:07
1 Answers
1
You need to build such a list yourself, typically by overriding __new__
.
class Weapon:
weapons = []
def __new__(cls, *args, **kwargs):
obj = super().__new__(cls, *args, **kwargs)
Weapon.weapons.append(obj)
Keep in mind that such a list will delay an instance from being garbage collected, unless you use weak references to track them. Also, there is no automatic removal of an instance from the list; to accomplish that, it may be simpler to use a dict
that maps an instance's id to the instance itself for easy lookup.

chepner
- 497,756
- 71
- 530
- 681