开发者

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

开发者 https://www.devze.com 2023-02-04 01:13 出处:网络
how to get name开发者_开发百科 of a class inside static method, i have inheritance and want name of derived class

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消