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
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.
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.
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.
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__
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With