How to get (sub)class name from a static method in Python?

后端 未结 2 901
情深已故
情深已故 2020-12-11 00:09

If I define:

class Bar(object):

    @staticmethod
    def bar():
        # code
        pass

class Foo(Bar):
    # code
    pass

Is it po

2条回答
  •  抹茶落季
    2020-12-11 00:15

    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
    

提交回复
热议问题