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

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

问题描述

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

我的装饰器:

  def specialTest(fn):文件名= fn .__ name__目录= fn .__模块__子目录= fn .__ class __.__ name__#我在哪里得到这个 

解决方案

如果 fn instancemethod ,则可以使用 fn.im_class .

>>>类Foo(对象):... def bar(自身):...         经过...>>> Foo.bar.im_class__main__.Foo

请注意,这在装饰器上将不会起作用,因为仅在定义了类之后,函数才转换为实例方法 (即,如果 @specialTest 用于装饰 bar ,它将不起作用;如果可能的话,那时候必须通过检查调用堆栈或同样不满意的方法来完成)./p>

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

解决方案

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

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

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