这是设置:
class Player(object):
def __init__(self, heigth):
self.heigth = heigth
print('do not forget that this should happen once!')
class Attacker(Player):
def __init__(self, heigth, goal_probability):
super().__init__(heigth)
self.goal_prob = goal_probability
def hit(self):
pass
# implementation
class Goalie(Player):
def __init__(self, heigth, save_probability=0.1):
super().__init__(heigth)
self.save_prob = save_probability
def catch(self):
pass
# implementation
class UniversalPlayer(Attacker, Goalie):
pass
up = UniversalPlayer(heigth=1.96, goal_probability=0.6)
这一切都按预期工作:MRO首先选择Attacker
,然后选择Goalie
。我用UniversalPlayer
的Attacker
签名调用__init__
的构造函数,用Goalie
的签名调用Player
的构造函数,它没问题,因为save_probability
有一个默认值,但问题是我无法选择save_probability
,除了在实例化up.save_probability
之后设置up
,我发现非常不优雅。
此外,如果Goalie
没有save_probability
的默认值,则此代码会引发异常。
有没有办法写UniversalPlayer
所以我也可以选择save_probability
,或者这里有一些根本问题无法解决?
__init__
的每个附加参数都需要有一个类来负责将它从super
的调用中删除,这样当最终调用object.__init__
时,你不会意外地将任何参数传递给它。此外,每个方法都必须接受任意参数并将其传递给下一个可能处理的方法。
# Player will be responsible for height
class Player(object):
def __init__(self, height, **kwargs):
super().__init__(**kwargs) # Player needs to use super too!
self.height = height
print('do not forget that this should happen once!')
# Attacker will be responsible for goal_probability
class Attacker(Player):
def __init__(self, height, goal_probability, **kwargs):
super().__init__(height, **kwargs)
self.goal_prob = goal_probability
def hit(self):
pass
# Goalie will be responsible for save_probability
class Goalie(Player):
def __init__(self, height, save_probability=0.1, **kwargs):
super().__init__(height, **kwargs)
self.save_prob = save_probability
def catch(self):
pass
# implementation
class UniversalPlayer(Attacker, Goalie):
pass
# Pass all arguments
# Life is easier if you stick to keyword arguments when using super().__init__
up = UniversalPlayer(height=1.96, goal_probability=0.6, save_probability=0.2)
现在,Attacker.__init__
是第一个被召唤的人。它使用goal_probability
,然后不将其传递给其他调用。它通过save_probability
接受**kwargs
并传递给Goalie.__init__
最终接收。请注意,Attacker.__init__
和Goalie.__init__
都不必在参数列表中明确包含height
;它也可以通过**kwargs
接受最终被Player.__init__
收到。
除了事实我不确定单独的类是否是处理这些的最佳方法,问题是你的构造函数不能处理未知的参数。允许他们使用*args, **kwargs
表示法。实际上,所有参数都将传递给每个__init__
,并忽略未使用的参数。
class Player(object):
def __init__(self, *args, **kwargs):
self.height = kwargs['height']
class Attacker(Player):
def __init__(self, goal_probability, *args, **kwargs):
super().__init__(*args, **kwargs)
self.goal_prob = goal_probability
def hit(self):
pass
# implementation
class Goalie(Player):
def __init__(self, save_probability, *args, **kwargs):
super().__init__(*args, **kwargs)
self.save_prob = save_probability
def catch(self):
pass
# implementation
class UniversalPlayer(Attacker, Goalie):
pass
up = UniversalPlayer(height=1.96, goal_probability=0.6, save_probability=0.2)