Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 dynamically assign base class

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.

  • abstract Piece class -> various derived pieces
  • Board class, has a composite of derived Pieces, and 8x8 matrix, and some methods
  • abstract Interface class -> CLI or
  • abstract Interface class -> GUI (also subclassing Tkinter)
  • Game class (for processing the game logic and main loop), which currently has a Board class member.

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.

like image 375
Kevin Avatar asked Feb 05 '26 08:02

Kevin


1 Answers

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!
like image 170
John La Rooy Avatar answered Feb 06 '26 21:02

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!