有一个用于Python的过载包。有了这个包,就可以重新定义方法,但是使用不同的类型提示和它的修饰器会发现,应该调用哪个重载的方法。
通用编码模式:
class foo:
def func(param):
if instance(param, int):
pass
elif instance(param, str):
pass
elif instance(param, list):
pass
else:
raise ValueError()带有@重载的:
class foo:
@overload
def func(param: int):
pass
@overload
def func(param: str):
pass
@overload
def func(param: list):
pass这是文档。
我的问题是:
发布于 2021-01-20 11:13:18
因为python3.4有一个核心API功能functools.singledispatch,它允许您注册重载函数。
从文件中
>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
... if verbose:
... print("Let me just say,", end=" ")
... print(arg)
>>> @fun.register
... def _(arg: int, verbose=False):
... if verbose:
... print("Strength in numbers, eh?", end=" ")
... print(arg)
>>> @fun.register
... def _(arg: list, verbose=False):
... if verbose:
... print("Enumerate this:")
... for i, elem in enumerate(arg):
... print(i, elem)在运行上述函数时(同样是从文档中):
>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Strength in numbers, eh? 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam注意:只输入第一个参数!
此外,还有一个(因为python3.8)的类方法的等价修饰器,称为functools.singledispatchmethod
发布于 2016-09-28 13:34:14
你必须用一个真正的代码来衡量它。
我非常快速地查看了这个库的代码,得出的结论很简单。它使用了大量的反射(检查包)和类型比较。检查包本身主要是由调试工具使用-它们总是减慢您的代码。
看看这些台词:
complexity = complexity_mapping[id]
if complexity & 8 and isinstance(arg, tuple):
element_type = tuple(type(el) for el in arg)
elif complexity & 4 and hasattr(arg, 'keys'):
element_type = (type(element), type(arg[element]))
else:
element_type = type(element)type_hints = typing.get_type_hints(func) if typing else func.__annotations__
types = tuple(normalize_type(type_hints.get(param, AnyType)) for param in parameters)请注意,这个包如果超过7个月,并且只有70颗星。Python不是Java..。这个包确实会对Python本身造成伤害:最好实现一些核心api方法,根据类型参数将调用委托给其他方法/对象--就像使用python一样。
https://stackoverflow.com/questions/39748842
复制相似问题