开发环境为WIN10+Python 3.6.5,直接上代码,看注释
wraps
from functools import wraps
def run1(f):
@wraps(f)
def wrapper(*args, **kwargs):
"""run1.wrapper's doc"""
return f(*args, **kwargs)
return wrapper
@run1
def main1():
"""main1's doc"""
pass
def run2(f):
def wrapper(*args, **kwargs):
"""run2.wrapper's doc"""
return f(*args, **kwargs)
return wrapper
@run2
def main2():
"""main2's doc"""
pass
print(main1.__name__)
print(main2.__name__)
print(main1.__doc__)
print(main2.__doc__)
结果是:
main1
wrapper
main1's doc
run2.wrapper's doc
偏函数 partial
from functools import partial
def fun(a, b=1, *args, **kwargs):
print(a, b, args, kwargs)
p = partial(fun, 1, 2, 3, 4, 5, 6, 7, 8, c=9)
p()
print(p.args)
print(p.func)
print(p.keywords)
结果是:
1 2 (3, 4, 5, 6, 7, 8) {'c': 9}
(1, 2, 3, 4, 5, 6, 7, 8)
<function fun at 0x000001BDB9AC1EA0>
{'c': 9}
如果是类里面的方式,使用
partialmethod
singledispath
from functools import singledispatch
@singledispatch
def fun(arg):
print('string:', arg)
@fun.register(int)
def _(arg):
print('int:', arg)
@fun.register(list)
def _(arg):
print('list:', arg)
def nothing(arg):
print('nothing')
fun.register(type(None), nothing)
print(fun.registry.keys())
fun('Hello')
fun(1)
fun([1, 2, 4])
fun(None)
注意,python没有所谓的函数重载,上面的方式,都只能针对函数的第一个参数有效。
版权声明:本文为nba199044原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。