Code Explanation:
1. Class Definition
class Item:
A new class named Item is defined.
This class represents an object that stores a price.
2. Constructor Method
def __init__(self, p):
self._price = p
__init__ is the constructor—runs automatically when you create an object.
It receives a parameter p.
self._price = p saves the value into a protected attribute _price.
The underscore _ indicates “don’t access directly” (a convention for protected attributes).
3. Property Decorator
@property
def price(self):
return self._price
@property converts the method price() into a read-only attribute.
Now you can access i.price without parentheses.
It returns the internal _price attribute safely.
4. Creating an Object
i = Item(200)
Creates an instance of the Item class.
The constructor sets _price = 200.
5. Accessing the Property
print(i.price)
Accessing i.price automatically calls the property method.
It returns _price, which is 200.
Output:
200
Final Output
200


0 Comments:
Post a Comment