41

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?

Max
  • 773
  • 8
  • 15
tadasajon
  • 14,276
  • 29
  • 92
  • 144

3 Answers3

51

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

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
14

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

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
13

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

Wil
  • 351
  • 3
  • 9