|
|
|
|
|
|
j*****k 发帖数: 1198 | 1 比如有下面一个decorator, 怎么调用?
def decorator(func,aa):
def wrapper(*args, **argd):
if aa:
func(*args, **argd)
return wrapper
@decorator
def myfunc(a1,a2)
or
@decorator(True)
def myfunc(a1,a2)
都不行。
谢谢 | k***r 发帖数: 4260 | 2 把aa定义在decorator外面试试看,比如
aa = False
def mydecorator(func):
def wrapper(*args, **argd):
if aa:
func(*args, **argd)
return wrapper
【在 j*****k 的大作中提到】 : 比如有下面一个decorator, 怎么调用? : def decorator(func,aa): : def wrapper(*args, **argd): : if aa: : func(*args, **argd) : return wrapper : @decorator : def myfunc(a1,a2) : or : @decorator(True)
| j*****k 发帖数: 1198 | 3 别人的decorator是定义好的,没法改
我这儿只是举个例子,想搞清楚怎么调用法
【在 k***r 的大作中提到】 : 把aa定义在decorator外面试试看,比如 : : aa = False : def mydecorator(func): : def wrapper(*args, **argd): : if aa: : func(*args, **argd) : return wrapper :
| i*****f 发帖数: 578 | 4 This decorator definition seems not make sense to me.
From your dec. definition, it's obvious it takes two arguments: func, aa. So:
@decorator
def f():
...
is transformed to:
decorator(func, aa)(f)
Your decorator is **got** to take exactly two arguments. If this is the case
, seems that the wrapper is not doing what you want.
Are you trying to do something like:
def decorator(aa):
def outer_wrapper(func):
def wrapper(*args, **argd):
if
【在 j*****k 的大作中提到】 : 比如有下面一个decorator, 怎么调用? : def decorator(func,aa): : def wrapper(*args, **argd): : if aa: : func(*args, **argd) : return wrapper : @decorator : def myfunc(a1,a2) : or : @decorator(True)
| j*****k 发帖数: 1198 | 5 yeah, the decorator has two parameters in which the first one is the
function.
just want to know how to use it.
Thanks
So:
case
【在 i*****f 的大作中提到】 : This decorator definition seems not make sense to me. : From your dec. definition, it's obvious it takes two arguments: func, aa. So: : @decorator : def f(): : ... : is transformed to: : decorator(func, aa)(f) : Your decorator is **got** to take exactly two arguments. If this is the case : , seems that the wrapper is not doing what you want. : Are you trying to do something like:
| d****e 发帖数: 251 | 6 如果要用@decorator调用,我觉得不能这么写decorator。这种写法你只能
直接
>>>new_func = decorator(func,aa)
这个tutorial写的挺清楚的,
http://www.artima.com/weblogs/viewpost.jsp?thread=240845
看最下面的Decorator Functions with Decorator Arguments.
【在 j*****k 的大作中提到】 : 比如有下面一个decorator, 怎么调用? : def decorator(func,aa): : def wrapper(*args, **argd): : if aa: : func(*args, **argd) : return wrapper : @decorator : def myfunc(a1,a2) : or : @decorator(True)
| r****t 发帖数: 10904 | 7 这个不是 decorator, 只是一个名字叫 decorator 的function,语法上看是一个
closure,
decorator is invoked with the function object as the only argument.
【在 j*****k 的大作中提到】 : yeah, the decorator has two parameters in which the first one is the : function. : just want to know how to use it. : Thanks : : So: : case
|
|
|
|
|
|
|