Get the class name of a decorated class method
Consider this scenario:
#!/usr/bin/env python # -*- coding: utf-8 -*- import functools def wrapmethod(f): @functools.wraps(f) def wrap(*args, **kwargs): print '>> %s' % (f.func_name) # Here I'll do pre-processing r = f(*args, **kwargs) # Here I'll do post-processing return r return wrap @wrapmethod def foo(): pass class Test(object): @wrapmethod def foo(self): pass test = Test() test.foo() foo()
It'll output this, as you can see executed in http://codepad.org/Y4xXyjJO:
>> foo >> foo
I want to know a way to print out Test.foo
in the first line, indicating the class which the method is linked to.
Any ideas? Is it ever possible?
Thank you in advance.
This is not easily possible. If you added self
as a first parameter of the inner function you could use self.__class__.__name__
to access the class name, but then it would break when decorating a classless function without arguments (and if it had arguments, it would consider the first argument as self
).
So unless there is a way to determine if a function has been called in an object context or not what you want do do is not possible.
Btw.. for what do you need that? It sounds like something which can be solved in a better way.
In fact, you can use inspect module to get the signature of a function, and supposing that you are following the convention of referring to the class object by the first argument 'self', you can do the following :
import inspect
def print_name(*_args):
def _print_name(fn):
def wrapper(*args, **kwargs):
try :
is_method = inspect.getargspec(fn)[0][0] == 'self'
except :
is_method = False
if is_method :
name = '{}.{}.{}'.format(fn.__module__, args[0].__class__.__name__, fn.__name__)
else :
name = '{}.{}'.format(fn.__module__, fn.__name__)
print (name)
return fn(*args,**kwargs)
return wrapper
return _print_name
this will print the method module, class and name or just the module and name, if this is a function
链接地址: http://www.djcxy.com/p/4882.html上一篇: 需要注意的问题
下一篇: 获取装饰类方法的类名