-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoop05.py
More file actions
52 lines (37 loc) · 1.73 KB
/
oop05.py
File metadata and controls
52 lines (37 loc) · 1.73 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
46
47
48
49
50
51
52
# creating a class
class Item:
#
pay_rate = 0.8 # The pay rate after 20% discount
# init is called automatically when an instance is created
# Using type hints for better code readability
# constructor
def __init__(self, name: str, price: float, quantity=0):
# Run validation to the received arguments
assert price >= 0, f"Price {price} is not greater than or equal to zero!"
assert quantity >=0, f"Quantity {quantity} is not greater than or equal to zero!"
# assigning to self object
self.name = name # instance attributes
self.price = price # instance attributes
self.quantity = quantity # instance attributes
def calculate_total_price(self):
return self.price * self.quantity
def apply_discount(self):
# self.price = self.price * Item.pay_rate # accessing class attribute via class
self.price = self.price * self.pay_rate # accessing class attribute via insta nce
item1 = Item("phone", 100, 5) # creating an instance of the Item class
item2 = Item("Laptop", 1000, 6) # creating another instance of the Item class
# whether a laptop has a numpad or not (not for phone)
item2.has_numpad = False # adding attribute to only item2 instance
print(Item.pay_rate) # accessing class attribute via class
print(item1.pay_rate) # accessing class attribute via instance (not recommended)
# check all attributes of Item class level
print(Item.__dict__)
# check all attributes of item1 instance level
print(item1.__dict__)
# applying discount
item1.apply_discount()
print(item1.price)
# applying discount at 30% for item
item2.pay_rate = 0.7 # changing pay_rate for only item2 instance
item2.apply_discount()
print(item2.price)