python inheritance: choose parent class using argument

北城余情 提交于 2021-01-27 14:48:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/57071752/python-inheritance-choose-parent-class-using-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!