I am writing a simple chess program to practice my OOP in python 3 and was wondering how to dynamically change (before class creation) the base class for a class definition. My class structure is this.
I initially implemented the Game class as having an interface data member that is defined during init but I'm finding myself sending a lot of the other internal Game data to the Interface composite member. I feel it would be more elegant to have the Game class be a subclass of either Interface subclass so the it could access their methods directly (and make them abstract).
However I want a version of the Game class that can do this dynamically so that I don't have to code it twice or inherit from both and make runtime decisions on which base class to use. I've currently done this by nesting the Game class inside a function like so.
def Game(ui):
class Game(ui):
...
return Game()
The crummy naming is part of the reason I don't like this solution. I want to be able to call the Game class on its own without explicitly using or acknowledging that I'm doing anything out of the ordinary.
Is there a way to do this with a metaclass or a class decorator? I have only been able to get them to affect class attributes, not the parent classes.
The class statement is "syntactic sugar" for
type(name, bases, dict)
You can create such a dynamic class using type like this
>>> class ui():
... def start(self): print("Started!")
...
>>> Game = type("Game", (ui,), {})
>>> game = Game()
>>> game.start()
Started!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With