Solution
This works:
class Action:
pass
class Move(Action):
pass
class Look(Action):
pass
actions = []
global_objs = list(globals().items())
for name, obj in global_objs:
if obj is not Action and isinstance(obj, type) and issubclass(obj, Action):
actions.append(obj())
print(actions)
prints:
[<__main__.Move object at 0x101916ba8>, <__main__.Look object at 0x101916be0>]
Steps
First, we get all names an an object in the current module:
global_objs = list(globals().items())
We need to convert into a list because in Python 3 items()
return a dictview object that reflects changes in the underlaying dictionary. Since we work in the same module, defining new objects will change this dictionary. Converting into a list solves this problem.
Next, we go through all objects. There are three conditions they need to fulfill to be subclass of Action
:
obj is not Action
- Since Action
is a subclass of itself, we need filter it out.
isinstance(obj, type)
- The object has to be a class. Otherwise, the test under 3. would not be possible.
issubclass(obj, Action)
- Finally, we can do our subclass test.
Now we can make instances of all filtered classes and append them to our list:
actions.append(obj())
Shorter version
If you are sure all classes are defined in one module or you even want all subclasses that are distributed over several modules, this would be much shorter:
>>> actions = [obj() for obj in Action.__subclasses__()]
>>> actions
[<__main__.Move at 0x10fc14fd0>, <__main__.Look at 0x10fc14668>]