简体   繁体   中英

python inheritance: choose parent class using argument

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM