小编Afi*_*fiz的帖子

将参数传递给装饰器函数

谁能告诉我如何将参数传递给装饰器调用函数?

def doubleIt(Onefunc):
    def doubleIn():
        return Onefunc()*Onefunc()
    return doubleIn

@doubleIt
def Onefunc():  
    return 5

print(Onefunc()) # it prints out 25. 
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试升级Onefunc()到:

@doubleIt
def Onefunc(x):
    return x
Run Code Online (Sandbox Code Playgroud)

我面临以下错误:

TypeError                                 
Traceback (most recent call last)
<ipython-input-17-6e2b55c94c06> in <module>()
      9 
     10 
---> 11 print(Onefunc(5))
     12 

TypeError: doubleIn() takes 0 positional arguments but 1 was given
Run Code Online (Sandbox Code Playgroud)

错误是自我解释,但我不知道如何更新doubleIn()函数来处理它.

python python-decorators

3
推荐指数
1
解决办法
238
查看次数

标签 统计

python ×1

python-decorators ×1