在以下代码段中,我试图定义一个工厂函数,该函数将基于参数返回从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
派生的类的实例。附言以上代码均未成功运行,因此可能包含其他错误。
最佳答案
您可以使用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)
关于python - Python:在类主体中动态创建子类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50174247/