Python函数重载

Python函数重载,第1张

Python函数重载

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

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

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

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

因此,我们应该能够做到多方法在python-或者,它也可称为:多分派。

多次调度

多重方法也称为多重调度

多种调度或多种方法是某些面向对象的编程语言的功能,其中可以基于多个参数的运行时(动态)类型来动态调度函数或方法。(维基百科)

Python不支持这个开箱1,但是,因为它发生,有一个优秀的Python包称为multipledispatch这正是这么做的。

解决方案

这是我们可能如何使用multidispatch 2包来实现你的方法的方法:

>>> from multipledispatch import dispatch>>> from collections import namedtuple  >>> from types import *  # we can test for lambda type, e.g.:>>> type(lambda a: 1) == LambdaTypeTrue>>> 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>>> 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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5640881.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存