-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path18_product_property_decorators.py
More file actions
45 lines (37 loc) · 1.03 KB
/
18_product_property_decorators.py
File metadata and controls
45 lines (37 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Product:
def __init__(self, name, price):
self.name = name
self._price = price # Protected attribute
@property
def price(self):
print("Getting price...")
return self._price
@price.setter
def price(self, value):
print("Setting price...")
if value < 0:
raise ValueError("Price cannot be negative")
self._price = value
@price.deleter
def price(self):
print("Deleting price...")
del self._price
# Example usage
if __name__ == "__main__":
product = Product("Laptop", 1000)
# Using getter
print(f"Current price: {product.price}")
# Using setter
product.price = 1200
print(f"New price: {product.price}")
# Trying to set negative price
try:
product.price = -100
except ValueError as e:
print(f"Error: {e}")
# Using deleter
del product.price
try:
print(product.price)
except AttributeError:
print("Price has been deleted")