假设Foo在其中的简单情况
class Foo:
def some_func(self):
print('hellow world')
我只能访问func所在的变量func:
func = Foo.some_func
我正在尝试从变量Foo
中获取func
类名
func
Out[6]: <function __main__.Foo.some_func>
func.__class__.__name__
Out[7]: 'function'
我期望得到Foo
可以做到吗?
答案 0 :(得分:5)
Python 3解决方案:
def get_class_name(func):
return func.__qualname__.split('.')[0]
__qualname__
方法实际上为Foo.some_func
打印了func
。
用.
分割字符串并采用第一个元素,它将完成工作。
Python 2和3解决方案:
def get_class_name(func):
return func.__str__().split('.')[0].split()[-1]
编辑:
在Python 3中,func.__str__()
打印<function Foo.some_func at 0x10c456b70>
。
在Python 2中,func.__str__()
打印<unbound method Foo.some_func>
。