通过@overload decorator简单重载方法和函数
overload的Python项目详细描述
通过@overload decorator简单地重载方法和函数。
这个模块允许一个为一个函数提供多个接口, 方法、类方法、静态方法或类。以下是一些注意事项 关于重载类,你这个奇怪的人。
根据调用参数选择适当的实现 模式。
例如:
>>> class A(object): ... @overload ... def method(self, a): ... return 'a' ... @method.add ... def method(self, a, b): ... return 'a, b' ... >>> a = A() >>> a.method(1) 'a' >>> a.method(1, 2) 'a, b'
重载处理fixed、keyword、variable(*args)和任意 关键字(**keywords)参数。
如果注释是类型,则它还处理注释:
>>> @overload ... def func(a:int): ... return 'int' ... >>> @func.add ... def func(a:str): ... return 'str' ... >>> func(1) 'int' >>> func('s') 'str' >>> func(1.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "overload.py", line 94, in f raise TypeError('invalid call argument(s)') TypeError: invalid call argument(s)
这个特性(目前通常是模块)需要python 3。
结果可调用的docstring和名称(即文档)将 匹配可调用重载的first的值。
重载类
重载类允许您根据 每个可选类型的新方法的构造参数。
但是有一个陷阱:new方法必须显式地调用 基类新方法,而不是像通常那样使用super()方法。这是 因为在被@重载之后,类是一个函数,而super() 不喜欢被传递函数。所以不要:
@overload class A(object): def __new__(cls): # this will fail because "A" is a function now return super(A, cls).__new__(cls)
您必须:
@overload class A(object): def __new__(cls): # must explicitly reference the base class return object.__new__(cls)
我将留给读者来证明他们使用@overload的合理性 上课。
版本历史(简略)
- 1.1更改了无效调用类型错误的文本。已删除调试打印。
- 1.0初始版本
有关使用许可证,请参见源文件的末尾。
我想知道这个模块是否有用-如果你使用它 请在https://www.ohloh.net/p/pyoverload