Reputation: 1587
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?
Upvotes: 3
Views: 545
Reputation: 1148
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.
Upvotes: 3