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

jononomo picture jononomo · Dec 30, 2012 · Viewed 24.4k times · Source

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?

Answer

BrenBarn picture BrenBarn · Dec 30, 2012

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