Skip to content Skip to sidebar Skip to footer

How To Get (sub)class Name From A Static Method In Python?

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

Solution 1:

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.

classBar(object):

    @classmethoddefbar(cls):
        # codeprint cls.__name__

classFoo(Bar):
    # codepass>>> Bar.bar()
Bar

>>> Foo.bar()
Foo

Solution 2:

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

classBar(object):
    @classmethoddefbar(cls):
        # codeprint(cls.__name__)

classFoo(Bar):
    # codepass

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

Solution 3:

As option, if you need determine class from staticmethod (not classmethod) I guess following code could be helpful:

classBar(object):
    @staticmethoddefbar():
        passclassFoo(Bar):
    pass


foo_instance = Foo()
bar_static_function = foo_instance.bar
class_name = bar_static_function.__qualname__.split(".")[0]
print(class_name)  # Foo

Post a Comment for "How To Get (sub)class Name From A Static Method In Python?"