Code Explanation:
1. Class Definition
class Test:
A class named Test is created.
Objects of this class will use the special methods __repr__ and __str__.
2. Defining __repr__ Method
def __repr__(self):
return "REPR"
__repr__ is a magic method that returns the official, developer-friendly string representation of an object.
It is used in debugging, lists of objects, the Python shell, etc.
This method returns the string "REPR".
3. Defining __str__ Method
def __str__(self):
return "STR"
__str__ is another magic method that defines the user-friendly string representation.
It is used when you call print(object) or str(object).
It returns the string "STR".
4. Creating an Object
t = Test()
An object t of class Test is created.
Now t has access to both __repr__ and __str__.
5. Printing the Object
print(t)
When printing an object, Python always calls __str__ first.
Since the class defines a __str__ method, Python uses it.
Therefore the printed output is:
STR
Final Output
STR


0 Comments:
Post a Comment