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

后端 未结 2 908
情深已故
情深已故 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:37

    If you need to find the class information, the appropriate way is to use @classmethod.

    class Bar(object):
        @classmethod
        def bar(cls):
            # code
            print(cls.__name__)
    
    class Foo(Bar):
        # code
        pass
    

    Now your bar method has a reference to the class as cls which is the actual class of the caller. And as shown in the code, cls.__name__ is the name of the class you are looking for.

    >>> Foo.bar()
    Foo
    >>> Bar.bar()
    Bar
    

提交回复
热议问题