271

我知道 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_bullet2add_bullet_with_really_long_name.

要解决一些答案:

  1. 不,我无法创建 Bullet 类层次结构,因为那太慢了。管理项目符号的实际代码是用 C 语言编写的,我的函数是 C API 的包装器。

  2. 我知道关键字参数,但检查各种参数组合变得很烦人,但默认参数有助于分配acceleration=0

4

19 回答 19

216

您所要求的称为多次调度。请参阅演示不同类型调度的Julia语言示例。

然而,在看之前,我们将首先解决为什么重载不是你在 Python 中真正想要的。

为什么不超载?

首先,需要了解重载的概念以及为什么它不适用于 Python。

当使用可以在编译时区分数据类型的语言时,可以在编译时进行选择。为编译时选择创建此类替代函数的行为通常称为重载函数。(维基百科

Python 是一种动态类型语言,因此重载的概念根本不适用于它。然而,一切都没有丢失,因为我们可以在运行时创建这样的替代函数:

在将数据类型识别推迟到运行时的编程语言中,替代函数的选择必须在运行时根据函数参数的动态确定类型进行。以这种方式选择替代实现的函数通常被称为方法。(维基百科

因此,我们应该能够在 Python 中执行方法——或者,也可以称为:multiple dispatch

多次派送

多方法也称为多调度

多分派或多方法是一些面向对象编程语言的特性,其中一个函数或方法可以基于其多个参数的运行时(动态)类型动态分派。(维基百科

Python 不支持开箱即用1,但是碰巧有一个名为multipledispatch的优秀 Python 包可以做到这一点。

解决方案

以下是我们如何使用multipledispatch 2包来实现您的方法:

>>> from multipledispatch import dispatch
>>> from collections import namedtuple
>>> from types import *  # we can test for lambda type, e.g.:
>>> type(lambda a: 1) == LambdaType
True

>>> Sprite = namedtuple('Sprite', ['name'])
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Curve = namedtuple('Curve', ['x', 'y', 'z'])
>>> Vector = namedtuple('Vector', ['x','y','z'])

>>> @dispatch(Sprite, Point, Vector, int)
... def add_bullet(sprite, start, direction, speed):
...     print("Called Version 1")
...
>>> @dispatch(Sprite, Point, Point, int, float)
... def add_bullet(sprite, start, headto, speed, acceleration):
...     print("Called version 2")
...
>>> @dispatch(Sprite, LambdaType)
... def add_bullet(sprite, script):
...     print("Called version 3")
...
>>> @dispatch(Sprite, Curve, int)
... def add_bullet(sprite, curve, speed):
...     print("Called version 4")
...

>>> sprite = Sprite('Turtle')
>>> start = Point(1,2)
>>> direction = Vector(1,1,1)
>>> speed = 100 #km/h
>>> acceleration = 5.0 #m/s**2
>>> script = lambda sprite: sprite.x * 2
>>> curve = Curve(3, 1, 4)
>>> headto = Point(100, 100) # somewhere far away

>>> add_bullet(sprite, start, direction, speed)
Called Version 1

>>> add_bullet(sprite, start, headto, speed, acceleration)
Called version 2

>>> add_bullet(sprite, script)
Called version 3

>>> add_bullet(sprite, curve, speed)
Called version 4

1. Python 3 目前支持单调度 2. 注意不要在多线程环境中使用 调度,否则会出现奇怪的行为。

于 2015-03-17T05:35:19.900 回答
118

当你展示它时,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):
  # implementation
my_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 speed

class pretty_and_fast_factory(object):
    def sprite(self):
       return pretty_sprite
    def speed(self):
       return 10000000000.0

my_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 issuing
my_character.bfactory = ugly_and_slow_factory()

# In the last example you can see abstract factory and "method
# overloading" (as you call it) in action 
于 2011-06-22T03:20:43.793 回答
102

您可以使用“roll-your-own”解决方案进行函数重载。这一篇抄自Guido van Rossum关于多方法的文章(因为Python中多方法和重载的区别不大):

registry = {}

class MultiMethod(object):
    def __init__(self, name):
        self.name = name
        self.typemap = {}
    def __call__(self, *args):
        types = tuple(arg.__class__ for arg in args) # a generator expression!
        function = self.typemap.get(types)
        if function is None:
            raise TypeError("no match")
        return function(*args)
    def register(self, types, function):
        if types in self.typemap:
            raise TypeError("duplicate registration")
        self.typemap[types] = function


def multimethod(*types):
    def register(function):
        name = function.__name__
        mm = registry.get(name)
        if mm is None:
            mm = registry[name] = MultiMethod(name)
        mm.register(types, function)
        return mm
    return register

用法是

from multimethods import multimethod
import unittest

# 'overload' makes more sense in this case
overload = multimethod

class Sprite(object):
    pass

class Point(object):
    pass

class Curve(object):
    pass

@overload(Sprite, Point, Direction, int)
def add_bullet(sprite, start, direction, speed):
    # ...

@overload(Sprite, Point, Point, int, int)
def add_bullet(sprite, start, headto, speed, acceleration):
    # ...

@overload(Sprite, str)
def add_bullet(sprite, script):
    # ...

@overload(Sprite, Curve, speed)
def add_bullet(sprite, curve, speed):
    # ...

目前最严格的限制是:

  • 不支持方法,只支持非类成员的函数;
  • 不处理继承;
  • 不支持 kwargs;
  • 注册新函数应该在导入时完成 事情不是线程安全的
于 2011-09-05T12:53:12.563 回答
53

一个可能的选择是使用这里详述的multipledispatch模块:http: //matthewrocklin.com/blog/work/2014/02/25/Multiple-Dispatch

而不是这样做:

def add(self, other):
    if isinstance(other, Foo):
        ...
    elif isinstance(other, Bar):
        ...
    else:
        raise NotImplementedError()

你可以这样做:

from multipledispatch import dispatch
@dispatch(int, int)
def add(x, y):
    return x + y    

@dispatch(object, object)
def add(x, y):
    return "%s + %s" % (x, y)

使用结果:

>>> add(1, 2)
3

>>> add(1, 'hello')
'1 + hello'
于 2014-07-29T16:19:36.890 回答
33

在 Python 3.4 PEP-0443 中。添加了单调度通用函数

这是 PEP 的简短 API 描述。

要定义泛型函数,请使用装饰器对其进行@singledispatch装饰。请注意,调度发生在第一个参数的类型上。相应地创建您的函数:

from functools import singledispatch
@singledispatch
def fun(arg, verbose=False):
    if verbose:
        print("Let me just say,", end=" ")
    print(arg)

要向函数添加重载实现,请使用泛型函数的 register() 属性。这是一个装饰器,接受一个类型参数并装饰一个实现该类型操作的函数:

@fun.register(int)
def _(arg, verbose=False):
    if verbose:
        print("Strength in numbers, eh?", end=" ")
    print(arg)

@fun.register(list)
def _(arg, verbose=False):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)
于 2016-01-01T13:04:05.857 回答
12

这种类型的行为通常使用polymorphism来解决(在 OOP 语言中) 。每种类型的子弹都将负责了解它的行进方式。例如:

class Bullet(object):
    def __init__(self):
        self.curve = None
        self.speed = None
        self.acceleration = None
        self.sprite_image = None

class RegularBullet(Bullet):
    def __init__(self):
        super(RegularBullet, self).__init__()
        self.speed = 10

class Grenade(Bullet):
    def __init__(self):
        super(Grenade, self).__init__()
        self.speed = 4
        self.curve = 3.5

add_bullet(Grendade())

def add_bullet(bullet):
    c_function(bullet.speed, bullet.curve, bullet.acceleration, bullet.sprite, bullet.x, bullet.y)


void c_function(double speed, double curve, double accel, char[] sprite, ...) {
    if (speed != null && ...) regular_bullet(...)
    else if (...) curved_bullet(...)
    //..etc..
}

将尽可能多的参数传递给存在的c_function,然后根据初始 c 函数中的值确定要调用哪个 c 函数。因此,Python 应该只调用一个 c 函数。一个 c 函数查看参数,然后可以适当地委托给其他 c 函数。

您实际上只是将每个子类用作不同的数据容器,但是通过在基类上定义所有潜在参数,子类可以自由地忽略它们不做的那些。

当出现一种新类型的项目符号时,您可以简单地在基础上再定义一个属性,更改一个 python 函数以便它传递额外的属性,以及一个检查参数和适当委托的 c_function。我想这听起来还不错。

于 2011-06-22T03:25:39.813 回答
12

根据定义,在 python 中重载函数是不可能的(请继续阅读以了解详细信息),但您可以使用简单的装饰器实现类似的功能

class overload:
    def __init__(self, f):
        self.cases = {}

    def args(self, *args):
        def store_function(f):
            self.cases[tuple(args)] = f
            return self
        return store_function

    def __call__(self, *args):
        function = self.cases[tuple(type(arg) for arg in args)]
        return function(*args)

你可以像这样使用它

@overload
def f():
    pass

@f.args(int, int)
def f(x, y):
    print('two integers')

@f.args(float)
def f(x):
    print('one float')


f(5.5)
f(1, 2)

修改它以使其适应您的用例。

概念的澄清

  • 函数调度:有多个同名函数。应该叫哪一个?两种策略
  • 静态/编译时调度又名“重载”)。根据参数的编译时类型决定调用哪个函数。在所有动态语言中,没有编译时类型,因此根据定义,重载是不可能的
  • 动态/运行时调度:根据参数的运行时类型决定调用哪个函数。这就是所有 OOP 语言所做的:多个类具有相同的方法,语言根据self/this参数的类型决定调用哪一个。但是,大多数语言只为this参数这样做。上面的装饰器将想法扩展到多个参数。

澄清一下,假设我们用假设的静态语言定义函数

void f(Integer x):
    print('integer called')

void f(Float x):
    print('float called')

void f(Number x):
    print('number called')


Number x = new Integer('5')
f(x)
x = new Number('3.14')
f(x)

使用静态调度(重载),您将看到两次“被调用的号码”,因为x已被声明为Number,这就是重载所关心的。使用动态调度,您将看到“整数调用,浮点调用”,因为这些x是调用函数时的实际类型。

于 2019-08-30T12:22:03.177 回答
10

@overload装饰器添加了类型提示(PEP 484)。

虽然这不会改变 Python 的行为,但它确实更容易理解正在发生的事情,并让 mypy 检测错误。

请参阅:类型提示PEP 484

于 2019-01-29T14:36:45.803 回答
7

通过传递关键字 args

def add_bullet(**kwargs):
    #check for the arguments listed above and do the proper things
于 2011-06-22T03:17:01.550 回答
6

我认为您的基本要求是在 Python 中使用类似 C/C++ 的语法,并且尽可能减少头痛。尽管我喜欢Alexander Poluektov 的回答,但它不适用于课程。

以下应该适用于类。它通过按非关键字参数的数量来区分(但它不支持按类型区分):

class TestOverloading(object):
    def overloaded_function(self, *args, **kwargs):
        # Call the function that has the same number of non-keyword arguments.
        getattr(self, "_overloaded_function_impl_" + str(len(args)))(*args, **kwargs)

    def _overloaded_function_impl_3(self, sprite, start, direction, **kwargs):
        print "This is overload 3"
        print "Sprite: %s" % str(sprite)
        print "Start: %s" % str(start)
        print "Direction: %s" % str(direction)

    def _overloaded_function_impl_2(self, sprite, script):
        print "This is overload 2"
        print "Sprite: %s" % str(sprite)
        print "Script: "
        print script

它可以像这样简单地使用:

test = TestOverloading()

test.overloaded_function("I'm a Sprite", 0, "Right")
print
test.overloaded_function("I'm another Sprite", "while x == True: print 'hi'")

输出:

这是重载 3
Sprite:我是 Sprite
开始:0
方向:右

这是重载 2
Sprite:我是另一个 Sprite
脚本:
while x == True: print 'hi'

于 2014-10-03T19:40:12.990 回答
5

Python 3.8 添加了functools.singledispatchmethod

将方法转换为单调度泛型函数。

要定义泛型方法,请使用 @singledispatchmethod 装饰器对其进行装饰。请注意,调度发生在第一个非自我或非 cls 参数的类型上,相应地创建您的函数:

from functools import singledispatchmethod


class Negator:
    @singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(self, arg: int):
        return -arg

    @neg.register
    def _(self, arg: bool):
        return not arg


negator = Negator()
for v in [42, True, "Overloading"]:
    neg = negator.neg(v)
    print(f"{v=}, {neg=}")

输出

v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a

@singledispatchmethod 支持与其他装饰器嵌套,例如 @classmethod。请注意,为了允许 dispatcher.register,singledispatchmethod 必须是最外层的装饰器。这是 Negator 类,其中 neg 方法被类绑定:

from functools import singledispatchmethod


class Negator:
    @singledispatchmethod
    @staticmethod
    def neg(arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(arg: int) -> int:
        return -arg

    @neg.register
    def _(arg: bool) -> bool:
        return not arg


for v in [42, True, "Overloading"]:
    neg = Negator.neg(v)
    print(f"{v=}, {neg=}")

输出:

v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a

相同的模式可用于其他类似的装饰器:staticmethod、abstractmethod 等。

于 2020-02-19T22:45:46.387 回答
4

要么在定义中使用多个关键字参数,要么创建一个Bullet层次结构,其实例被传递给函数。

于 2011-06-22T03:14:48.957 回答
3

我认为Bullet具有相关多态性的类层次结构是要走的路。您可以通过使用元类有效地重载基类构造函数,以便调用基类导致创建适当的子类对象。下面是一些示例代码来说明我的意思的本质。

更新

代码已修改为在 Python 2 和 3 下运行以保持相关性。这是以一种避免使用 Python 的显式元类语法的方式完成的,该语法在两个版本之间有所不同。

为了实现该目标,通过在创建基类时显式调用元类来创建类的实例BulletMetaBase(而不是使用类属性或通过关键字参数,具体取决于 Python 版本)。BulletMetaBullet__metaclass__=metaclass

class BulletMeta(type):
    def __new__(cls, classname, bases, classdict):
        """ Create Bullet class or a subclass of it. """
        classobj = type.__new__(cls, classname, bases, classdict)
        if classname != 'BulletMetaBase':
            if classname == 'Bullet':  # Base class definition?
                classobj.registry = {}  # Initialize subclass registry.
            else:
                try:
                    alias = classdict['alias']
                except KeyError:
                    raise TypeError("Bullet subclass %s has no 'alias'" %
                                    classname)
                if alias in Bullet.registry: # unique?
                    raise TypeError("Bullet subclass %s's alias attribute "
                                    "%r already in use" % (classname, alias))
                # Register subclass under the specified alias.
                classobj.registry[alias] = classobj

        return classobj

    def __call__(cls, alias, *args, **kwargs):
        """ Bullet subclasses instance factory.

            Subclasses should only be instantiated by calls to the base
            class with their subclass' alias as the first arg.
        """
        if cls != Bullet:
            raise TypeError("Bullet subclass %r objects should not to "
                            "be explicitly constructed." % cls.__name__)
        elif alias not in cls.registry: # Bullet subclass?
            raise NotImplementedError("Unknown Bullet subclass %r" %
                                      str(alias))
        # Create designated subclass object (call its __init__ method).
        subclass = cls.registry[alias]
        return type.__call__(subclass, *args, **kwargs)


class Bullet(BulletMeta('BulletMetaBase', (object,), {})):
    # Presumably you'd define some abstract methods that all here
    # that would be supported by all subclasses.
    # These definitions could just raise NotImplementedError() or
    # implement the functionality is some sub-optimal generic way.
    # For example:
    def fire(self, *args, **kwargs):
        raise NotImplementedError(self.__class__.__name__ + ".fire() method")

    # Abstract base class's __init__ should never be called.
    # If subclasses need to call super class's __init__() for some
    # reason then it would need to be implemented.
    def __init__(self, *args, **kwargs):
        raise NotImplementedError("Bullet is an abstract base class")


# Subclass definitions.
class Bullet1(Bullet):
    alias = 'B1'
    def __init__(self, sprite, start, direction, speed):
        print('creating %s object' % self.__class__.__name__)
    def fire(self, trajectory):
        print('Bullet1 object fired with %s trajectory' % trajectory)


class Bullet2(Bullet):
    alias = 'B2'
    def __init__(self, sprite, start, headto, spead, acceleration):
        print('creating %s object' % self.__class__.__name__)


class Bullet3(Bullet):
    alias = 'B3'
    def __init__(self, sprite, script): # script controlled bullets
        print('creating %s object' % self.__class__.__name__)


class Bullet4(Bullet):
    alias = 'B4'
    def __init__(self, sprite, curve, speed): # for bullets with curved paths
        print('creating %s object' % self.__class__.__name__)


class Sprite: pass
class Curve: pass

b1 = Bullet('B1', Sprite(), (10,20,30), 90, 600)
b2 = Bullet('B2', Sprite(), (-30,17,94), (1,-1,-1), 600, 10)
b3 = Bullet('B3', Sprite(), 'bullet42.script')
b4 = Bullet('B4', Sprite(), Curve(), 720)
b1.fire('uniform gravity')
b2.fire('uniform gravity')

输出:

creating Bullet1 object
creating Bullet2 object
creating Bullet3 object
creating Bullet4 object
Bullet1 object fired with uniform gravity trajectory
Traceback (most recent call last):
  File "python-function-overloading.py", line 93, in <module>
    b2.fire('uniform gravity') # NotImplementedError: Bullet2.fire() method
  File "python-function-overloading.py", line 49, in fire
    raise NotImplementedError(self.__class__.__name__ + ".fire() method")
NotImplementedError: Bullet2.fire() method
于 2011-06-22T15:00:12.523 回答
2

使用带有默认值的关键字参数。例如

def add_bullet(sprite, start=default, direction=default, script=default, speed=default):

在直子弹与弯曲子弹的情况下,我会添加两个函数:add_bullet_straightadd_bullet_curved.

于 2011-06-22T03:15:43.563 回答
2

您可以在 Python 中非常轻松地实现函数重载。这是一个使用floatsand的示例integers

class OverloadedFunction:
    def __init__(self):
        self.D = {int: self.f_int, float: self.f_float}
    
    def __call__(self, x):
        return self.D[type(x)](x)
    
    def f_int(self, x):
        print('Integer Function')
        return x**2
    
    def f_float(self, x):
        print('Float Function (Overloaded)')
        return x**3

# f is our overloaded function
f = OverloadedFunction()

print(f(3 ))
print(f(3.))

# Output:
# Integer Function
# 9
# Float Function (Overloaded)
# 27.0

代码背后的主要思想是,一个类包含您想要实现的不同可能的功能,并且 Dictionary 用作router,根据输入将您的代码指向正确的功能type(x)

PS1。如果是自定义类,例如Bullet1,您可以按照类似的模式初始化内部字典,例如self.D = {Bullet1: self.f_Bullet1, ...}. 其余代码相同。

PS2。所提出的解决方案的时间/空间复杂度也相当不错,平均O(1)每次操作的成本。

于 2021-06-04T00:12:36.537 回答
2

这个库以一种直接的 Python 方式支持它。从下面的自述文件中复制一个示例。

from plum import dispatch

@dispatch
def f(x: str):
    return "This is a string!"
    

@dispatch
def f(x: int):
    return "This is an integer!"

>>> f("1")
'This is a string!'

>>> f(1)
'This is an integer!'
于 2021-06-27T18:27:36.903 回答
2

在 Python 中重载方法很棘手。但是,可以使用传递字典、列表或原始变量。

我已经为我的用例尝试了一些东西,这可以帮助理解人们重载方法。

让我们举个例子:

一个类重载方法,调用不同类的方法。

def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):

从远程类传递参数:

add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}

或者

add_bullet(sprite = 'test', start=Yes, headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}

因此,正在处理来自方法重载的列表、字典或原始变量。

试试你的代码。

于 2016-12-30T06:36:41.843 回答
1

您可以使用以下 Python 代码实现此目的:

@overload
def test(message: str):
    return message

@overload
def test(number: int):
    return number + 1
于 2022-01-13T05:36:37.300 回答
-1

你也可以试试这个代码。我们可以尝试任意数量的参数

# Finding the average of given number of arguments
def avg(*args):   # args is the argument name we give
    sum = 0
    for i in args:
        sum += i
        average = sum/len(args)   # Will find length of arguments we given
    print("Avg: ", average)

# call function with different number of arguments
avg(1,2)
avg(5,6,4,7)
avg(11,23,54,111,76)
于 2021-10-14T00:41:18.910 回答