34

how to get name of a class inside static method, i have inheritance and want name of derived class

IN following example what shall be there in place of XXX in method my_name()

class snake()
   @staticmethod
   def my_name():  
      print XXX.__name___

class python (snake)
   pass
class cobra (snake)
   pass

python.my_name()
# I want output to be python

cobra.my_name()   
# I want output to be cobra
Skilldrick
  • 69,215
  • 34
  • 177
  • 229
Tiwari
  • 1,014
  • 2
  • 12
  • 22
  • Possible duplicate of [How to get (sub)class name from a static method in Python?](http://stackoverflow.com/questions/3596641/how-to-get-subclass-name-from-a-static-method-in-python) – Mr_and_Mrs_D Apr 27 '17 at 09:21

2 Answers2

62

I'm pretty sure that this is impossible for a static method. Use a class method instead:

class Snake(object):
    @classmethod
    def my_name(cls):  
        print cls.__name__
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 7
    As Lennart said, it's not "impossible", but it's a very bad idea. Pretend I never said the following, but ... you could do it using the `inspect` module with `inspect.currentframe()`, and then loading and searching through the source file to find the name of the function and then its class. :-) – Ben Hoyt Jan 14 '11 at 14:38
12

A static method in Python is for all intents and purposes just a function. It knows nothing about the class, so you should not do it. It's probably possible, most things tend do be. But it's Wrong. :)

And in this case, you clearly do care about the class, so you don't want a static method. So use a class method.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251