Get Python function's owning class from decorator

前端 未结 2 1958
庸人自扰
庸人自扰 2021-02-09 07:54

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 modu

相关标签:
2条回答
  • 2021-02-09 08:20

    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).

    0 讨论(0)
  • 2021-02-09 08:28

    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__)).

    0 讨论(0)
提交回复
热议问题