2024-04-29 05:25:42 发布
网友
我在PY有个装修师。它是一种方法,以函数为参数。我想基于传递的函数创建一个目录结构。我正在使用父目录的模块名,但希望使用子目录的类名。我不知道如何获取拥有fn对象的类的名称。
我的装饰师:
def specialTest(fn): filename = fn.__name__ directory = fn.__module__ subdirectory = fn.__class__.__name__ #WHERE DO I GET THIS
如果fn是instancemethod,则可以使用fn.im_class。
fn
instancemethod
fn.im_class
>>> class Foo(object): ... def bar(self): ... pass ... >>> Foo.bar.im_class __main__.Foo
注意,这将不从decorator工作,因为函数只在定义类之后转换为实例方法(即,如果使用@specialTest来修饰bar,它将不工作;如果这甚至是可能的,在这一点上,必须通过检查调用堆栈或类似的不愉快的事情来完成。
@specialTest
bar
在Python 2中,可以对method对象使用im_class属性。在Python 3中,它将是__self__.__class__(或type(method.__self__))。
im_class
__self__.__class__
type(method.__self__)
如果
fn
是instancemethod
,则可以使用fn.im_class
。注意,这将不从decorator工作,因为函数只在定义类之后转换为实例方法(即,如果使用
@specialTest
来修饰bar
,它将不工作;如果这甚至是可能的,在这一点上,必须通过检查调用堆栈或类似的不愉快的事情来完成。在Python 2中,可以对method对象使用
im_class
属性。在Python 3中,它将是__self__.__class__
(或type(method.__self__)
)。相关问题 更多 >
编程相关推荐