Code Explanation:
1. Class Definition
class Box:
Defines a new class named Box — a blueprint for creating Box objects that will hold a value n and expose a computed property.
2. Constructor
def __init__(self, n):
self._n = n
__init__ is the constructor; it runs when you create a Box instance.
The parameter n is passed in when constructing the object.
self._n = n stores n in the instance attribute _n. By convention the single underscore (_n) signals a “protected” attribute (meant for internal use), but it is still accessible from outside.
3. Property Definition
@property
def triple(self):
return self._n * 3
@property turns the triple() method into a read-only attribute called triple.
When you access b.triple, Python calls this method behind the scenes.
return self._n * 3 computes and returns three times the stored value _n. This does not change _n — it only computes a value based on it.
4. Creating an Instance
b = Box(6)
Creates a Box object named b, passing 6 to the constructor.
Inside __init__, self._n is set to 6.
5. Accessing the Property and Printing
print(b.triple)
Accessing b.triple invokes the triple property method, which computes 6 * 3 = 18.
print outputs the returned value.
Final Output
18


0 Comments:
Post a Comment