获取Python中当前执行的classmethod的模块和类

问题描述 投票:0回答:1

对于名为

some.module
的模块中存在的代码,如下所示:

class MyClass:

 @classmethod
 def method(cls):
  # do something
  pass

我想知道标记为“做某事”的块中的模块名称、类名称和方法名称是什么。在上面的例子中,那就是:

  • 模块
    some.module
  • 班级
    MyClass
  • 方法
    method

我知道

inspect.stack()
,我可以从中获取函数/方法名称,但我找不到其余的数据。

python introspection
1个回答
0
投票

这些是最直接的方法:

import inspect

class MyClass:

 @classmethod
 def method(cls):
  print("module:", __name__)
  print("class:", cls.__name__)
  print("method:", inspect.currentframe().f_code.co_name)
© www.soinside.com 2019 - 2024. All rights reserved.