I'm having trouble designing some classes. I want my user to be able to use the Character() class by passing in an argument for the type of character (e.g. fighter/wizard).
Dummy code:
class CharClass():
def __init__(self, level):
self.level = level
class Fighter(CharClass):
# fighter stuff
pass
class Wizard(CharClass):
# wizard stuff
pass
class Character(): #?
def __init__(self, char_class):
# should inherit from Fighter/Wizard depending on the char_class arg
pass
For example, after calling:
c = Character(char_class='Wizard')
I want c to inherit all the attributes/methods from the Wizard class.
I have lots of classes so I want to avoid writing separate classes for each, I want a single entrance point for a user (Character).
Question: can it be done this way? Or is this a silly way to approach it?
You can make use of the less known feature of the type function:
def Character(char_class):
return type("Character", (char_class,), {})
type can be used to dynamically create a class. First parameter is the class name, second are the classes to inherit from and third are the initial attributes.
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