For example, if I'm decorating a method like so
例如,如果我正在装饰这样的方法
def my_decorator(fn):
# Do something based on the class that fn is a method of
def decorated_fn(*args, **kwargs):
fn(*args, **kwargs)
return decorated_fn
class MyClass(object):
@my_decorator
def my_method(self, param):
print "foo"
Is it possible in my_decorator to determine where fn came from?
是否可以在my_decorator中确定fn的来源?
2 个解决方案
#1
3
Short answer: No.
简答:没有。
Longer answer: You can do it by mucking about in the stack trace (see the inspect
module) but it's not a great idea.
更长的答案:你可以通过在堆栈跟踪中查看(参见检查模块)来做到这一点,但这不是一个好主意。
Full answer: At the time the function gets decorated, it's still an unbound function. Try the following:
完整答案:在函数被装饰时,它仍然是一个未绑定的函数。请尝试以下方法:
def my_dec(fn):
print dir(fn) # Has "func_code" and "func_name"
return fn
class A(object):
@my_dec
def test(self):
pass
print dir(A.test) # Has "im_class" and "im_self"
You can see that the raw function gets passed to the decorator, while the bound function is available after the class is declared.
您可以看到原始函数被传递给装饰器,而在声明类之后绑定函数可用。
The way to accomplish this is to just the function decorator in conjunction with either a metaclass or a class decorator. In either case, the function decorator can set a flag on the function, and the metaclass or class decorator can look for it and do the appropriate thing.
实现此目的的方法是将函数装饰器与元类或类装饰器结合使用。在任何一种情况下,函数装饰器都可以在函数上设置一个标志,并且元类或类装饰器可以查找它并执行适当的操作。
#2
1
No. You'll have to defer it until decorated_fn()
is called.
不。在调用decorated_fn()之前,您必须将其推迟。
#1
3
Short answer: No.
简答:没有。
Longer answer: You can do it by mucking about in the stack trace (see the inspect
module) but it's not a great idea.
更长的答案:你可以通过在堆栈跟踪中查看(参见检查模块)来做到这一点,但这不是一个好主意。
Full answer: At the time the function gets decorated, it's still an unbound function. Try the following:
完整答案:在函数被装饰时,它仍然是一个未绑定的函数。请尝试以下方法:
def my_dec(fn):
print dir(fn) # Has "func_code" and "func_name"
return fn
class A(object):
@my_dec
def test(self):
pass
print dir(A.test) # Has "im_class" and "im_self"
You can see that the raw function gets passed to the decorator, while the bound function is available after the class is declared.
您可以看到原始函数被传递给装饰器,而在声明类之后绑定函数可用。
The way to accomplish this is to just the function decorator in conjunction with either a metaclass or a class decorator. In either case, the function decorator can set a flag on the function, and the metaclass or class decorator can look for it and do the appropriate thing.
实现此目的的方法是将函数装饰器与元类或类装饰器结合使用。在任何一种情况下,函数装饰器都可以在函数上设置一个标志,并且元类或类装饰器可以查找它并执行适当的操作。
#2
1
No. You'll have to defer it until decorated_fn()
is called.
不。在调用decorated_fn()之前,您必须将其推迟。