Get Python function's owning class from decorator

☆樱花仙子☆ 提交于 2019-12-21 04:33:10

问题


I have a decorator in PY. It is a method and takes the function as a parameter. I want to create a directory structure based based on the passed function. I am using the module name for the parent directory but would like to use the classname for a subdirectory. I can't figure out how to get the name of the class that owns the fn object.

My Decorator:

def specialTest(fn):
    filename = fn.__name__
    directory = fn.__module__
    subdirectory = fn.__class__.__name__ #WHERE DO I GET THIS

回答1:


If fn is an instancemethod, then you can use fn.im_class.

>>> class Foo(object):
...     def bar(self):
...         pass
...
>>> Foo.bar.im_class
__main__.Foo

Note that this will not work from a decorator, because a function is only transformed into an instance method after the class is defined (ie, if @specialTest was used to decorate bar, it would not work; if it's even possible, doing it at that point would have to be done by inspecting the call stack or something equally unhappy).




回答2:


In Python 2 you can use im_class attribute on the method object. In Python 3, it'll be __self__.__class__ (or type(method.__self__)).



来源:https://stackoverflow.com/questions/7680446/get-python-functions-owning-class-from-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!