Code Explanation:1. Class Definition
class Info:
This line defines a new class named Info.
A class is a blueprint for creating objects.
Objects created from this class will store a value and display it in a custom format.
2. Constructor Method
def __init__(self, n):
self.n = n
__init__ is the constructor method.
It runs automatically when a new object is created.
n is the value passed while creating the object.
self.n = n stores that value inside the object as an instance variable.
3. __repr__ Magic Method
def __repr__(self):
return f"Info[{self.n}]"
__repr__ is a special (magic) method used to define how the object looks when printed.
It returns a formatted string showing the value of n.
So if n = 11, it will return:
Info[11]
4. Object Creation
i = Info(11)
This creates an object i of the Info class.
The constructor assigns:
i.n = 11
5. Printing the Object
print(i)
print(i) automatically calls the __repr__ method.
It prints the formatted string returned by __repr__.
Final Output
Info[11]


0 Comments:
Post a Comment