问题描述
我在设计一些类时遇到问题.我希望我的用户能够通过传入角色类型的参数(例如战斗机/巫师)来使用 Character() 类.
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).
虚拟代码:
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
例如调用后:c = Character(char_class='Wizard')
我希望 c 从 Wizard 类继承所有属性/方法.我有很多类,所以我想避免为每个类编写单独的类,我想要一个用户(角色)的入口点.
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?
推荐答案
您可以利用 type
函数的鲜为人知的特性:
You can make use of the less known feature of the type
function:
def Character(char_class):
return type("Character", (char_class,), {})
type
可用于动态创建类.第一个参数是类名,第二个是要继承的类,第三个是初始属性.
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.
这篇关于python继承:使用参数选择父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!