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

泪湿孤枕 提交于 2020-06-24 11:23:23

问题


I have the following code:

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

    def print_class_name_again(self):
        print self.__class__.__name__

if __name__ == '__main__':
    obj_one = ObjectOne()
    obj_one.print_class_name()
    obj_one.print_class_name_again()

The output is:

type
ObjectOne

I would like the output to be:

ObjectOne
ObjectOne

But I would like to keep test_cls as a class method via the @classmethod decorator.

How can I accomplish this?


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/14094961/python-how-can-i-get-the-class-name-from-within-a-class-method-using-classm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!