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?
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.
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.
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.
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.
A classmethod receives the class as its argument. That's why you're calling it cls
. Just do cls.__name__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With