I'm creating a game in which I have a somewhat complex method for creating entities.
When a level is loaded, the loading code reads a bunch of YAML files that contain attributes of all the different possible units. Using the YAML file, it creates a so-called EntityResource
object. This EntityResource object serves as the authoritative source of information when spawning new units. The goal is twofold:
- Deter cheating by implementing a hash check on the output of the YAML file
- Aid in debugging by having all unit information come from a single, authoritative source.
These EntityResource
objects are then fed into an EntityFactory
object to produce units of a specific type.
My question is as follows. Is there a way to create sublcasses of EntityResource
dynamically, based on the contents of the YAML file being read in?
Also, I would like each of these YAML-file-derived subclasses to be assigned a singleton metaclass. Any caveats?
I'm not sure if this is what you're looking for, but you can use
type
to create subclasses dynamically:Edit: To understand how
type
works, you just need to translate how would you write the class and translate that into atype
call. For example, if you want to write something like:then, that would be translated to:
where:
It is possible to create subclasses on the fly. This does not mean that you should. In any case, I will provide a mechanism.
The bases attribute in each class tells you the inheritance chain:
So,
__bases__
is a tuple with the "inheritance bases". You can replace this tuple (you cannot "append to it" or "pop from it" because it is a a tuple, and tuples are immutable). For example, say that you have a "mixin class" which adds functionalities to some animal subclasses but not others:Produces the following output:
A lot of people consider MixIn classes evil. And they may be right! You can imagine that if you mess up the bases attribute, you pretty much destroyed your program. So, there it is - you can dynamically change the inheritance of an object, but it does not mean you should (probably abstract classes or concept implementation?)
When I hear "creating subclasses on the fly" I understand "create objects that behave differently on the fly", which is really a question of configuration.
Is there anything you need that you can't get by just reading in some data and creating an object that decides how it is going to behave based on what it reads?
Here's the metaphor: I'm a handy guy -- I can put together any IKEA item you throw at me. But I'm not a different person each time, I'm just the same handy guy reading a different set of diagrams and looking for different kinds of screws and pieces of wood. That's my reasoning for subclassing not being the natural solution here.