Code Explanation:
1. Class Definition
class Box:
You define a new class named Box, which will hold a value and provide a computed property.
2. Constructor Method
def __init__(self, n):
self._n = n
__init__ is the constructor that runs when an object is created.
It takes one argument n.
The value is stored in a protected attribute _n.
3. Property Decorator
@property
def value(self):
return self._n * 2
Explanation:
@property converts the method value() into an attribute-like getter.
Accessing b.value now calls this method automatically.
It returns twice the stored number (_n * 2).
4. Creating an Object
b = Box(5)
Creates an instance of Box with _n = 5.
5. Printing the Property
print(b.value)
Accesses the property value.
Internally calls value() method.
It returns 5 * 2 = 10.
Final Output
10


0 Comments:
Post a Comment