27

我有以下代码:

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()

输出是:

type
ObjectOne

我希望输出为:

ObjectOne
ObjectOne

但我想通过装饰器将其保留test_cls为类方法。@classmethod

我怎样才能做到这一点?

4

3 回答 3

40

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

于 2012-12-30T21:46:18.003 回答
12

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

于 2012-12-30T21:45:58.780 回答
10

我有一个类似的问题,想要获取日志记录的类名和函数/方法名。

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

inspect.stack()[0][3] 给出模块名称。(你必须进口检查)。

干杯

于 2018-12-28T14:28:13.033 回答