2010-10-19 81 views
3

例如,如果我在装饰,像这样是否可以确定函数是哪种类的方法?

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" 

的方法是否有可能在my_decorator以确定其中,fn是从哪里来的?

+1

这可能会有所帮助:http://stackoverflow.com/questions/3564049/decorator-changing-function-status-from-method-to-function/3564110#3564110 – carl 2010-10-19 23:36:02

回答

3

简短的回答:第

再回应:您可以通过瞎的堆栈跟踪(见inspect模块)做到这一点,但它不是一个好主意。

完整答案:当函数被装饰时,它仍然是一个未绑定的函数。请尝试以下操作:

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" 

你可以看到原始函数被传递到装饰,而类被声明后绑定功能可用。

完成此操作的方法只是将函数装饰器与metaclassclass decorator一起使用。无论哪种情况,函数装饰器都可以在函数上设置一个标志,元类或类装饰器可以查找它并执行相应的操作。

1

不可以。您必须推迟到decorated_fn()被调用。

相关问题