Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python how to get name of a class inside its static method

Tags:

python

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 
like image 256
Tiwari Avatar asked Jan 14 '11 14:01

Tiwari


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.

How can I find the class name inside class?

The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.

How do you call a class method from a static method?

A static method has no access to the class as well as, for instance, variables since it does not get a starting argument such as cls and self. It is not possible to change the object's or class's state as an outcome. ClassName. method_name() and an object of the class can be used to call the class method.


2 Answers

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__ 
like image 194
Sven Marnach Avatar answered Sep 19 '22 16:09

Sven Marnach


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.

like image 44
Lennart Regebro Avatar answered Sep 20 '22 16:09

Lennart Regebro