【问题标题】:Is it possible to determine which class a function is a method of?是否可以确定函数是哪个类的方法?
【发布时间】:2010-10-19 23:05:28
【问题描述】:

例如,如果我正在装饰这样的方法

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 的来源?

【问题讨论】:

标签: python methods introspection


【解决方案1】:

简答:不。

更长的答案:您可以通过在堆栈跟踪中搞砸来做到这一点(请参阅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 结合使用。在任何一种情况下,函数装饰器都可以在函数上设置一个标志,元类或类装饰器可以查找它并执行相应的操作。

【讨论】:

    【解决方案2】:

    没有。您必须将其推迟到调用 decorated_fn() 为止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 2011-10-10
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 2012-05-30
      相关资源
      最近更新 更多