Python函数重载我知道Python不支持方法重载,但我遇到了一个问题,我似乎无法以一种漂亮的Pythonic方式解决这个问题。我正在制作一个角色需要射击各种子弹的游戏,但是如何编写不同的功能来制作这些子弹呢?例如,假设我有一个函数可以创建一个以给定速度从A点到B点行进的子弹。我会写一个这样的函数: def add_bullet(sprite, start, headto, speed):
... Code ...但我想写其他功能来创建子弹,如: def add_bullet(sprite, start, direction, speed):
def add_bullet(sprite, start, headto, spead, acceleration):
def add_bullet(sprite, script): # For bullets that are controlled by a script
def add_bullet(sprite, curve, speed): # for bullets with curved paths
... And so on ...等等有很多变化。有没有更好的方法来做到这一点,而不使用这么多的关键字参数导致它快速变得有点难看。重命名每个功能,因为你要么是非常糟糕过add_bullet1,add_bullet2或add_bullet_with_really_long_name。要解决一些问题:不,我无法创建Bullet类层次结构,因为它太慢了。管理项目符号的实际代码在C中,我的函数是围绕C API的包装器。我知道关键字参数,但检查各种参数组合变得烦人,但默认参数有助于分配 acceleration=0
3 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
当你提出它时,Python确实支持“方法重载”。事实上,你刚才描述的内容在Python中以很多不同的方式实现是微不足道的,但我会选择:
class Character(object): # your character __init__ and other methods go here def add_bullet(self, sprite=default, start=default, direction=default, speed=default, accel=default, curve=default): # do stuff with your arguments
在上面的代码中,default
这些参数是合理的默认值,或者None
。然后,您可以仅使用您感兴趣的参数调用该方法,Python将使用默认值。
你也可以这样做:
class Character(object): # your character __init__ and other methods go here def add_bullet(self, **kwargs): # here you can unpack kwargs as (key, values) and # do stuff with them, and use some global dictionary # to provide default values and ensure that ``key`` # is a valid argument... # do stuff with your arguments
另一种方法是直接将所需函数挂接到类或实例:
def some_implementation(self, arg1, arg2, arg3): # implementationmy_class.add_bullet = some_implementation_of_add_bullet
另一种方法是使用抽象工厂模式:
class Character(object): def __init__(self, bfactory, *args, **kwargs): self.bfactory = bfactory def add_bullet(self): sprite = self.bfactory.sprite() speed = self.bfactory.speed() # do stuff with your sprite and speedclass pretty_and_fast_factory(object): def sprite(self): return pretty_sprite def speed(self): return 10000000000.0my_character = Character(pretty_and_fast_factory(), a1, a2, kw1=v1, kw2=v2)my_character.add_bullet() # uses pretty_and_fast_factory# now, if you have another factory called "ugly_and_slow_factory" # you can change it at runtime in python by issuingmy_character.bfactory = ugly_and_slow_factory()# In the last example you can see abstract factory and "method# overloading" (as you call it) in action
添加回答
举报
0/150
提交
取消