![]() |
Problem solving illustration. |
Hello, everyone! Good evening. Today, we'll tackle another coding problem. We'll delve into creating classes, inheritance, instances, dictionary looping, and more. This will test our foundational Python programming skills. Let’s get started!
Coding Prompt: 1
Create a class called Item that contains a dictionary of shopping items and their prices
- The class Item should not take any arguments when initialized.
- Inside the class, define a variable items representing of items database.
- Items are phone (price 1000), headphones (price 100).
Coding Prompt: 2
Create a class Cart that inherits from the Item class and represents a user's shopping cart
- Inside Cart, define an empty variable to store items that the user selects for purchase.
- Define a variable that keeps track of the total cost of the selected items.
- Use super() to initialize the parent class.
Coding Prompt: 3
Write a method adds() that takes argument of item selected by user.
- When you instantiate a Cart() object, it returns the total quantity of items selected by the user.
Coding Prompt: 4
Write a method total() that calculates the total price of all items in the user's cart.
- Return the total price as the result.
Coding Prompt: 5
Process the class like this:
print(cart.total()) # should be: 0
cart.adds('phone')
print(len(cart.userSelectedItems)) # Should be: 1
print(cart.total()) # Should be: 1000
cart.adds('headphones')
cart.adds('headphones')
print(len(cart.userSelectedItems)) # Should be 3
print(cart.total()) # Should be: 1200
Answer:
That’s all for today. Have a wonderful day!