【发布时间】:2014-11-12 15:38:15
【问题描述】:
我面临以下问题:
- 有一个基类
Unit,它有几个属性,例如id,type,name,skills, ... - 有不同类型的单元,其中一些具有
health、attack或tribe等附加属性,因此自然也存在相关子类HealthUnit、AttackUnit等。 - 有一些单位具有多个这些属性,例如
HealthAttackUnit,或HealthAttackTribeUnit。
我想避免这样的编码:
class Unit(object):
def __init__(self, id, type, name, skills):
self.id= id
self.type= type
self.name= name
self.skills= skills
class HealthUnit(Unit):
def __init__(self, id, type, name, skills, health):
Unit.__init__(self, id, type, name, skills)
self.health= health
class AttackUnit(Unit):
def __init__(self, id, type, name, skills, attack):
Unit.__init__(self, id, type, name, skills)
self.attack= attack
class HealthAttackUnit(HealthUnit, AttackUnit):
def __init__(self, id, type, name, skills, health, attack):
HealthUnit.__init__(self, id, type, name, skills, health)
AttackUnit.__init__(self, id, type, name, skills, attack)
出于显而易见的原因。
我尝试使用 dict 解包作为解决方法,有点像这样:
class HealthUnit(Unit):
def __init__(self, health, **args):
Unit.__init__(self, **args)
self.health= health
但即使这样也有很多重复的代码:
class HealthAttackUnit(HealthUnit, AttackUnit):
def __init__(self, health, attack, **args):
HealhUnit.__init__(self, health=health, **args)
AttackUnit.__init__(self, attack=attack, **args)
class HealthAttackTribeUnit(HealthUnit, AttackUnit, TribeUnit):
def __init__(self, health, attack, tribe, **args):
HealhUnit.__init__(self, health=health, **args)
AttackUnit.__init__(self, attack=attack, **args)
TribeUnit.__init__(self, tribe=tribe, **args)
另外,这将调用Unit.__init__ 多次,这不太理想。
所以,问题是:有没有更好、更少复制/粘贴的方法?
更新: dict 解包非常好,但使用关键字参数调用所有构造函数仍然有点烦人。我更喜欢没有**kwargs 的解决方案,但我猜可能没有?
【问题讨论】:
-
如果您使用
super(),则不必分别调用每个继承的__init__- 参见例如stackoverflow.com/q/576169/3001761。你也需要使用*args, **kwargs。 -
除非您实例化
HealthUnit和AttackUnit的对象,否则您可能希望对mixins 感兴趣。 -
@poke 那些是 mixins,确定吗?
-
@DanielRoseman 因为他们继承自一般的
Unit,而不是只是提供健康或攻击的东西,我不这么认为。 -
@DanielRoseman:不,它们不是 mixins,因为需要实例化
HealthUnit和AttackUnit对象。
标签: python python-2.7 inheritance multiple-inheritance