安装装饰器模块:
$ pip install decorator
修改以下内容的定义
args_as_ints()
:import decorator
@decorator.decorator
def args_as_ints(f, args, kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(args, **kwargs)@args_as_ints
def funny_function(x, y, z=3):
“”“Computes xy + 2z”“”
return xy + 2zprint funny_function(“3”, 4.0, z=”5”)
22help(funny_function)
Help on function funny_function in module main:funny_function(x, y, z=3)Computes xy + 2z
Python 3.4以上
functools.wraps()自Python
3.4起,来自stdlib的文件就保留了签名:
import functoolsdef args_as_ints(func): @functools.wraps(func) def wrapper(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return func(*args, **kwargs) return wrapper@args_as_intsdef funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*zprint(funny_function("3", 4.0, z="5"))# 22help(funny_function)# Help on function funny_function in module __main__:## funny_function(x, y, z=3)# Computes x*y + 2*z
functools.wraps()至少从Python 2.5开始就可用,但是它不在那里保留签名:
help(funny_function)# Help on function funny_function in module __main__:## funny_function(*args, **kwargs)# Computes x*y + 2*z
注意:
*args, **kwargs代替
x, y, z=3。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)