Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python inheritance: choose parent class using argument

Tags:

python

oop

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?

like image 487
Dan Avatar asked Aug 04 '26 06:08

Dan


1 Answers

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.

like image 105
Louis Saglio Avatar answered Aug 06 '26 19:08

Louis Saglio



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!