Ste*_*n G 3 python methods class
假设Foo是简单的情况
class Foo:
def some_func(self):
print('hellow world')
Run Code Online (Sandbox Code Playgroud)
我只能访问变量func,其中func是:
func = Foo.some_func
Run Code Online (Sandbox Code Playgroud)
我试图Foo从变量中获取类名func
func
Out[6]: <function __main__.Foo.some_func>
func.__class__.__name__
Out[7]: 'function'
Run Code Online (Sandbox Code Playgroud)
Foo 无论如何,我期待得到那样做?
Python 3解决方案:
def get_class_name(func):
return func.__qualname__.split('.')[0]
Run Code Online (Sandbox Code Playgroud)
__qualname__方法实际打印Foo.some_func为func.
拆分字符串.并获取第一个元素,它应该完成这项工作.
Python 2&3解决方案:
def get_class_name(func):
return func.__str__().split('.')[0].split()[-1]
Run Code Online (Sandbox Code Playgroud)
编辑:
在Python 3中,func.__str__()打印<function Foo.some_func at 0x10c456b70>.
在Python 2中,func.__str__()打印<unbound method Foo.some_func>.
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |