Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 determine the class name Foo?

like image 474
Jean-Pierre Chauvel Avatar asked Aug 29 '10 21:08

Jean-Pierre Chauvel


People also ask

Can we call static method with class name Python?

You can also call static methods on classes directly, because a static method doesn't require an object instance as a first argument - which is the point of the static method.

What is the difference between Staticmethod and Classmethod in Python?

The static method does not take any specific parameter. Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class.

What does @staticmethod do in Python?

The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.


1 Answers

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 
like image 144
Dave Kirby Avatar answered Sep 30 '22 09:09

Dave Kirby