Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 912
tadasajon Avatar asked Dec 30 '12 21:12

tadasajon


People also ask

How do you call a class method inside a class method?

Use self. f() to call a class method inside of __init__ Within the method definition of __init__(self) , call self. f() where f is the name of the class method.

How do I get the class name of an object in Python?

Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance. Use the type() function and __name__ to get the type or class of the Object/Instance. Using the decorator to get the type or class of the Object/Instance.

How do you find the class of a function in Python?

To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.

How do you call a class method from another class method in Python?

Call method from another class in a different class in Python. we can call the method of another class by using their class name and function with dot operator. then we can call method_A from class B by following way: class A: method_A(self): {} class B: method_B(self): A.


1 Answers

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

like image 89
BrenBarn Avatar answered Sep 22 '22 13:09

BrenBarn