Python - how can I get the class name from within a class method - using @classmethod

前端 未结 3 1881
太阳男子
太阳男子 2021-02-12 22:07

I have the following code:

class ObjectOne(object):
    @classmethod
    def print_class_name(cls):
        print cls.__class__.__name__

    def print_class_nam         


        
相关标签:
3条回答
  • 2021-02-12 22:47

    It's cls.__name__. cls already points to the class, and now you're getting the name of its class (which is always type).

    0 讨论(0)
  • 2021-02-12 22:53

    I had a similar question and wantend to get the class name for logging and the function/method name.

    __name__ :  gives the program name
    __class__.__name__ gives the class name
    

    inspect.stack()[0][3] gives the module name. (you have to import inspect).

    Cheers

    0 讨论(0)
  • 2021-02-12 23:07

    A classmethod receives the class as its argument. That's why you're calling it cls. Just do cls.__name__.

    0 讨论(0)
提交回复
热议问题