Code Explanation:
1. Class Definition
class Item:
A class named Item is created.
It will represent an object that stores a price.
2. Initializer Method
def __init__(self, p):
self._p = p
Explanation:
__init__ is the constructor of the class.
It takes one argument p (the price).
The value is stored in a protected attribute _p.
_p means: "this is intended for internal use, but still accessible."
3. Property Decorator
@property
def price(self):
return self._p + 10
Explanation:
@property turns the method price() into a read-only attribute.
Calling i.price will actually execute this method.
It returns self._p + 10, meaning:
The actual price returned is 10 more than the stored _p value.
4. Creating an Object
i = Item(50)
Explanation:
An instance of Item is created with _p = 50.
5. Accessing the Property
print(i.price)
Explanation:
Calls the price property.
Internally runs: return self._p + 10
_p = 50, so result = 60
Output
60
600 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment