Code Explanation:
1. Class Definition
class Box:
You define a class named Box, which will represent an object containing a number.
2. Constructor Method
def __init__(self, n):
self._n = n
Explanation:
__init__ is the constructor that runs when a new object of Box is created.
It receives the parameter n.
self._n = n stores the value in an attribute named _n.
The single underscore (_n) indicates it is a protected variable (a naming convention).
3. Property Decorator
@property
def double(self):
return self._n * 2
Explanation:
@property turns the method double() into a read-only attribute.
When you access b.double, Python will automatically call this method.
It returns double of the stored number (_n * 2).
4. Creating an Object
b = Box(7)
Explanation:
Creates a new object b of class Box.
Calls __init__(7), so _n becomes 7.
5. Accessing the Property
print(b.double)
Explanation:
Accesses the property double.
Calls the method internally and returns 7 * 2 = 14.
The output printed is:
Output
14


0 Comments:
Post a Comment