如何使用检查从绑定方法中获取 class 名称?

How to get class name from bound method using inspect?

class MyClass:
  def my_method(self):
    print(get_context())

MyClass().my_method()

我需要下一行:

MyClass::my_method

sys._getframe(2).f_code.co_name 只给我 "my_method"。如何获得 class 名称?

您可以通过从 self 调用 __class__.__name__ 来获取您的班级名称。

class Foo(object):
    def bar(self):
        print(self.__class__.__name__)

Foo().bar()

输出: 福