【发布时间】:2013-06-21 01:10:21
【问题描述】:
Python 3.3: 我可以装饰一个函数以忽略所有与命名参数不匹配的位置参数吗?
import functools
def ignore_star_args():
def wrapper(function_):
@functools.wraps(function_)
def wrapped(*f_args):
return function_(/*only named args*/)
return wrapped
return wrapper
@ignore_star_args()
def list_args(a, b, *args):
# two positional arguments
return [a, b] + list(args)
>>> list_args(1, 2, "non-positional arg")
[1, 2]
【问题讨论】:
-
我不理解你的例子。在
list_args(1, 2, "non-positional arg")中,"non-positional arg"仍然是一个位置参数,尽管名称令人困惑。 -
顺便说一下,“命名位置参数”(或有时是“固定位置参数”)是我自己对“位置或关键字和仅位置,但不是可变位置”的简写,因为实际上,这些东西并没有正式的术语……
标签: python python-3.x decorator