从装饰器获取Python函数的拥有类 [英] Get Python function's owning class from decorator

查看:1073
本文介绍了从装饰器获取Python函数的拥有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PY有个装饰师。它是一个方法,并将该函数作为参数。我想基于传递的函数创建一个目录结构。我使用模块名称为父目录,但想使用类名为子目录。我不知道如何获得拥有fn对象的类的名称。

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.

我的装饰:

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


推荐答案

如果 fn 是实例方法,那么您可以使用 fn.im_class

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

请注意, em> 从装饰器工作,因为一个函数只是在之后被转换为一个实例方法(即 @specialTest 用于装饰 bar ,它不会工作;如果甚至可能,在这一点上做它将必须通过检查调用堆栈或一些同等不愉快)。

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

这篇关于从装饰器获取Python函数的拥有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆