使用decorator重载python 2函数。

p2-overload的Python项目详细描述


重载python函数,使其根据参数的数量和类型有不同的行为。

安装

pip install p2-overload

用法

from overload import *

# types and number or agrs:
@overload(int)
def quantify(n):
    return 'quantify' * n

@overload(str)
def quantify(s):
    return s * 2

@overload(str, int)
def quantify(s, n):
    return s * n

assert quantify(2) == 'quantifyquantify'
assert quantify('bye') == 'byebye'
assert quantify('xy', 3) == 'xyxyxy'

# predicates on args
@overload(int, int)
def step(start, step):
    return start + step

@overload(int, callable)
def step(start, succ):
    return succ(start)

# use tuple of types
@overload((list, tuple))
def twice(coll):
    return coll + coll

# use custom predicates
from whatever import _

@overload(_ < 2) # same as lambda x: x < 2
def fib(n):
    return n

@overload(int)
def fib(n):
    return fib(n-1) + fib(n-2)

待办事项

  • 支持命名参数和可选参数
  • 省略号

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何向第二个组合框模型项添加数组值从第一个组合框所选项获取数组名称?   使用Java与WebSphere的SSL握手错误   eclipse线程“main”Java中的第一个Java程序异常。lang.NoClassDefFoundError   java将Javafx应用作为Web应用移植的最佳方式   IDE的java右JVM文件夹   java如何在基本适配器中停止文本到语音   java If block使用substring和equals方法以假值执行   在本例中,如何在java中返回多个值?   java第二个主类在maven构建期间覆盖第一个主类   如何在java中设置运行时ArrayList的泛型类型?   java从主机读取文件