Python:在类主体中动态创建子类

2024-10-05 18:47:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码片段中,我试图定义一个工厂函数,它将根据参数返回从Hero派生的不同类的对象。你知道吗

class Hero:
    Stats = namedtuple('Stats', ['health', 'defence', 'attack',
                                 'mana', 'experience'])
    RaceMaxStats = OrderedDict([
        ('Knight', Stats(100, 170, 150, 0, inf)),
        ('Barbarian', Stats(120, 150, 180, 0, inf)),
        ('Sorceress', Stats(50, 42, 90, 200, inf)),
        ('Warlock', Stats(70, 50, 100, 180, inf))
    ])

    @staticmethod
    def def_race(race: str):
        return type(race, (Hero,), {'max': Hero.RaceMaxStats[race]})

    Races = OrderedDict([
        (race, Hero.def_race(race)) for race in RaceMaxStats.keys()
    ])

    def __init__(self, lord, health, defence, attack, mana, experience):
        self.race = self.__class__.__name__
        self.lord = lord
        self.stats = Hero.Stats(min(health, self.max.health),
                                min(defence, self.max.defence),
                                min(attack, self.max.attack),
                                min(mana, self.max.mana),
                                min(experience, self.max.experience))

    @staticmethod
    def summon(race, *args, **kwargs):
        return Hero.Races[race](*args, **kwargs)

为了以后像这样使用它:

knight = Hero.summon('Knight', 'Ronald', 90, 150, 150, 0, 20)
warlock = Hero.summon('Warlock', 'Archibald', 50, 50, 100, 150, 50)

问题是我无法初始化子类,因为Hero尚未定义:

    (race, Hero.def_race(race)) for race in RaceMaxStats.keys()
NameError: name 'Hero' is not defined

显然,如果我用直接的type()调用替换静态方法调用,我仍然需要定义Hero。我的问题是如何最好地实施这种工厂。优先级是summon()方法保留相同的签名,并返回从Hero派生的类的实例。你知道吗

另外,上面的代码都没有成功运行过,因此可能包含其他错误。你知道吗


Tags: selfdefstatsminmaxinfexperiencemana
3条回答

你能试试吗:

Hero('Knight', 'Ronald', 90, 150, 150, 0, 20).summon()

或者:

hero = Hero('Knight', 'Ronald', 90, 150, 150, 0, 20)
hero.summon()

在类定义之后,执行Hero.knight = Hero.summon(...)等操作。你知道吗

您可以使用classmethods并将您的Races变量定义为一个方法,该方法在第一次调用类变量后缓存其结果。它看起来是这样的:

@classmethod
def def_race(cls, race: str):
    return type(race, (cls,), {'max': cls.RaceMaxStats[race]})

_Races = None

@classmethod
def Races(cls, race):
    if cls._Races is None:
        cls._Races = OrderedDict([
           (race, cls.def_race(race)) for race in cls.RaceMaxStats.keys()
        ])
    return cls._Races[race]

@classmethod
def summon(cls, race, *args, **kwargs):
    return cls.Races(race)(*args, **kwargs)

相关问题 更多 >