且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Python 中的静态方法获取(子)类名?

更新时间:2023-09-13 23:34:28

用类方法替换静态方法.这将在调用时传递类,因此您可以从中获取类名.

Replace the staticmethod with a classmethod. This will be passed the class when it is called, so you can get the class name from that.

class Bar(object):

    @classmethod
    def bar(cls):
        # code
        print cls.__name__

class Foo(Bar):
    # code
    pass

>>> Bar.bar()
Bar

>>> Foo.bar()
Foo