Python Classes and Objects

 

Classes and Objects

Attributes of an Object

Attributes can be set or accessed using

.
(dot) character.

Code

class Mobile:
def __init__(self, model, storage):
self.model = model
self.storage = storage
obj = Mobile("iPhone 12 Pro", "128GB")
print(obj.model)
PYTHON

Output

iPhone 12 Pro

Accessing in Other Methods

We can also access and update properties in other methods.

Code

class Mobile:
def __init__(self, model):
self.model = model
def get_model(self):
print(self.model)
obj_1 = Mobile("iPhone 12 Pro")
obj_1.get_model()
PYTHON

Output

iPhone 12 Pro

Updating Attributes

It is recommended to update attributes through methods.

Code

class Mobile:
def __init__(self, model):
self.model = model
def update_model(self, model):
self.model = model
obj_1 = Mobile("iPhone 12")
print(obj_1.model)
obj_1.update_model("iPhone 12 Pro")
print(obj_1.model)
PYTHON
Collapse

Output

iPhone 12
iPhone 12 Pro

Modeling Class

Let’s model the scenario of shopping cart of ecommerce site.

The features a cart should have

  • can add an item
  • can remove an item from cart
  • update quantity of an item
  • to show list of items in cart
  • to show total price for the items in the cart

Code

class Cart:
def __init__(self):
self.items = {}
self.price_details = {"book": 500, "laptop": 30000}
def add_item(self, item_name, quantity):
self.items[item_name] = quantity
def remove_item(self, item_name):
del self.items[item_name]
def update_quantity(self, item_name, quantity):
self.items[item_name] = quantity
def get_cart_items(self):
cart_items = list(self.items.keys())
return cart_items
def get_total_price(self):
total_price = 0
for item, quantity in self.items.items():
total_price += quantity * self.price_details[item]
return total_price
cart_obj = Cart()
cart_obj.add_item("book", 3)
cart_obj.add_item("laptop", 1)
print(cart_obj.get_total_price())
cart_obj.remove_item("laptop")
print(cart_obj.get_cart_items())
cart_obj.update_quantity("book", 2)
print(cart_obj.get_total_price())
 
PYTHON
Collapse

Output

31500
['book']
1000

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form