Python 是否有可能确定哪一类函数是一种方法?
例如,如果我正在这样装饰一个方法Python 是否有可能确定哪一类函数是一种方法?,python,methods,introspection,Python,Methods,Introspection,例如,如果我正在这样装饰一个方法 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_me
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来自何处?否。您必须将其推迟到调用
装饰的\u fn()
时进行。简短回答:否
更长的答案:您可以通过在堆栈跟踪中乱搞来实现(请参阅检查
模块),但这不是一个好主意
完整答案:在函数被修饰时,它仍然是一个未绑定的函数。请尝试以下操作:
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"
您可以看到原始函数被传递给装饰器,而绑定函数在类声明后可用
实现这一点的方法是将函数装饰器与或结合使用。在这两种情况下,函数装饰器都可以在函数上设置一个标志,元类或类装饰器可以查找它并执行相应的操作。这可能会有帮助: