Code Explanation:
๐น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
This class will define how its objects are represented as strings.
๐น 2. __str__ Method
def __str__(self):
return "STR"
✅ Explanation:
__str__ is a magic method used for user-friendly string representation.
It is called when:
print(obj)
str(obj)
Here, it returns:
"STR"
๐น 3. __repr__ Method
def __repr__(self):
return "REPR"
✅ Explanation:
__repr__ is another magic method used for:
Debugging
Developer-friendly representation
It is called when:
You type obj in interpreter
Or when __str__ is not defined
๐น 4. Creating Object
obj = Test()
✅ Explanation:
An object obj of class Test is created.
No constructor (__init__) is defined, so default is used.
๐น 5. Printing Object
print(obj)
✅ What happens internally:
Python follows this priority:
Call __str__()
If not available → call __repr__()
๐ In this case:
__str__ exists → used
So:
obj.__str__()
returns:
"STR"
๐ฏ Final Output
STR

0 Comments:
Post a Comment