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

Jean-Pierre Chauvel picture Jean-Pierre Chauvel · Aug 29, 2010 · Viewed 11.5k times · Source

If I define:

class Bar(object):

    @staticmethod
    def bar():
        # code
        pass

class Foo(Bar):
    # code
    pass

Is it possible for a function call Foo.bar() to determine the class name Foo?

Answer

Dave Kirby picture Dave Kirby · Aug 29, 2010

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