【问题标题】:Access Class Name From a Class Method从类方法访问类名
【发布时间】:2018-07-25 12:04:09
【问题描述】:

假设 Foo 的简单情况

class Foo:
    def some_func(self):
        print('hellow world')

我只能访问 func 所在的变量 func :

func = Foo.some_func

我正在尝试从变量 func 中获取 Foo 类名

func
Out[6]: <function __main__.Foo.some_func>
func.__class__.__name__
Out[7]: 'function'

我期待得到Foo 有什么办法吗?

【问题讨论】:

  • 不回答,只是一个注释,你可以在 help(func) 的解释器中找到它

标签: python class methods


【解决方案1】:

Python 3 解决方案:

def get_class_name(func):
    return func.__qualname__.split('.')[0]

__qualname__ 方法实际上为func 打印Foo.some_func

通过. 分割字符串并获取第一个元素,它应该可以完成这项工作。

Python 2 & 3 解决方案:

def get_class_name(func):
    return func.__str__().split('.')[0].split()[-1]

编辑:

在 Python 3 中,func.__str__() 打印出&lt;function Foo.some_func at 0x10c456b70&gt;

在 Python 2 中,func.__str__() 打印出 &lt;unbound method Foo.some_func&gt;

【讨论】:

  • 谢谢,正是我想要的。不知道__qualname__
  • 我也是。我正在使用 ipython 并查找可能有用的 dunder 方法。我想我今天学到了一些东西!
  • @StevenG 请问你用这个做什么?只是对这个的用例感兴趣。
  • 我在装饰器中使用它,装饰器用于表示任务的多个类中。当 task.run() 被调用时,我得到任务名称(类名)并将日志发送到 SQL
  • object.__str__(func) 即使在 func.__str__ 被覆盖时也能正常工作。
猜你喜欢
  • 2018-10-21
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2015-07-09
  • 2012-04-28
相关资源
最近更新 更多