我知道Python不支持方法重载,但我遇到了一个似乎无法用Python的方式解决的问题。
我正在制作一个游戏,一个角色需要拍摄各种子弹,但我如何编写不同的功能来创建这些子弹?例如,假设我有一个函数,它创建一个子弹以给定的速度从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
。
要回答一些问题:
不,我不能创建项目符号类层次结构,因为这太慢了。管理项目符号的实际代码在C中,我的函数是C API的包装器。
我知道关键字参数,但是检查参数的各种组合越来越烦人,但是默认参数有助于分配,比如acceleration=0
Python在呈现时确实支持“方法重载”。事实上,您刚才所描述的在Python中以许多不同的方式实现是微不足道的,但是我将继续:
在上面的代码中,
default
是这些参数的一个合理的默认值,或者None
。然后,您可以只使用感兴趣的参数调用该方法,Python将使用默认值。你也可以这样做:
另一种选择是直接将所需函数挂接到类或实例:
另一种方法是使用抽象的工厂模式:
您所要求的是称为多重调度。请参阅演示不同类型分派的Julia语言示例。
然而,在讨论这个问题之前,我们将首先讨论为什么在python中重载并不是您真正想要的。
为什么不超载呢?
首先,需要理解重载的概念以及为什么它不适用于python。
Python是一种dynamically类型语言,因此重载的概念并不适用于它。但是,并不是所有的都丢失了,因为我们可以在运行时创建这样的替代函数:
因此,我们应该能够在python中执行多方法,或者,也就是我们所说的:多分派。
多次调度
多方法也称为多分派:
Python不支持这种现成的1,但是,碰巧有一个名为multipledispatch的优秀Python包可以做到这一点。
解决方案
下面是我们如何使用multipledispatch2包来实现您的方法:
一。Python 3目前支持single dispatch
2。注意不要在多线程环境中使用multipledispatch,否则会出现奇怪的行为。
您可以使用“roll your own”解决方案来重载函数。这个是从Guido van Rossum's article关于多方法复制的(因为mm和python中的重载没有什么区别):
用法是
目前最具限制性的限制是:
相关问题 更多 >
编程相关推荐