Python在decorator接收单个参数时的歧义性

2024-05-21 15:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个只得到一个参数的decorator,即

@Printer(1)
def f():
    print 3

所以,天真地,我试着:

^{pr2}$

这是可以的,但它也可以作为一个不接收arg的装饰器工作,即

@Printer
def a():
   print 3

我怎样才能防止呢?在


Tags: 参数defarg装饰decoratorprinterprintpr2
3条回答

你确定它不用争论就行吗?如果我忽略了它们,我会收到以下错误消息:

Traceback (most recent call last):
  File "/tmp/blah.py", line 28, in ?
    a()
TypeError: __call__() takes exactly 2 arguments (1 given)

但是,如果基于类的定义对您不起作用,您可以尝试这个替代定义。在

^{pr2}$

好吧,它已经被有效地阻止了,从某种意义上说,调用a()不起作用。在

但是要在定义函数时停止它,我想您必须更改__init__来检查num的类型:

def __init__(self,num):
    if callable(num):
        raise TypeError('Printer decorator takes an argument')
    self.__num=num

不过,我不知道这样做是否值得。它已经不能按原样工作了;您实际上要求在duck类型的语言中强制执行参数类型。在

我想不出一个理想的答案,但是如果您强制Printer类用关键字参数实例化,它就永远不会尝试通过decorator本身实例化,因为它只处理非关键字参数:

def __init__(self,**kwargs):
     self.__num=kwargs["num"]

。。。在

^{pr2}$

相关问题 更多 >