Code Explanation:
1. Class Definition
class Item:
This defines a new class called Item.
Classes are blueprints for objects, which can have attributes and methods.
2. Constructor Method
def __init__(self, p):
self._price = p
__init__ is the constructor, called automatically when a new object is created.
p is passed as a parameter when creating the object.
self._price = p stores the price in a protected attribute _price.
By convention, a single underscore _ indicates that this attribute should not be accessed directly outside the class.
3. Property Decorator
@property
def price(self):
return self._price + 20
@property turns the price() method into a read-only attribute.
When you access i.price, it automatically calls this method.
The method returns _price plus 20, effectively adding a fixed markup to the price.
Benefit: You can compute or validate values dynamically while keeping a clean attribute-like access.
4. Creating an Object
i = Item(80)
Creates an object i of the class Item with _price = 80.
The constructor initializes the protected attribute _price.
5. Accessing the Property
print(i.price)
Accessing i.price calls the price property method.
The method calculates _price + 20 = 80 + 20 = 100.
print outputs:
100
Final Output:
100


0 Comments:
Post a Comment