Junior — Middle
Explain the purpose of the __class__ method in Python and how it is used inside classes.
sobes.tech AI
Answer from AI
In Python, __class__ is a special attribute of an object that points to the class to which the object belongs. It allows access to the class itself from an instance.
Example usage:
class MyClass:
def print_class_name(self):
print(self.__class__.__name__)
obj = MyClass()
obj.print_class_name() # Outputs: MyClass
This is useful when you need to get information about the class of an object inside a method, for logging, creating new instances, or accessing class attributes.
Note: __class__ is not a method but an attribute of the object.