A vending machine is a real-world object that dispenses items when money is inserted. It has functionalities such as displaying available products, accepting payments, dispensing items, and returning change.
In this example, we will create a VendingMachine
class that includes:
✅ Attributes: List of available products and their prices, machine balance.
✅ Methods: Display products, accept payment, dispense items, and return change.
✅ Encapsulation: Secure handling of balance and transactions.
This example demonstrates object-oriented programming (OOP) by encapsulating data (products, balance) and behavior (transactions, dispensing items) in a structured way.
class VendingMachine:
"""Class representing a vending machine."""
def __init__(self):
"""Initialize products and balance."""
self.products = {
"A1": {"name": "Soda", "price": 1.50},
"A2": {"name": "Chips", "price": 2.00},
"A3": {"name": "Candy", "price": 1.00}
}
self.balance = 0.0 # Machine balance
def display_products(self):
"""Display available products and their prices."""
print("Available Products:")
for code, product in self.products.items():
print(f"{code}: {product['name']} - ${product['price']:.2f}")
def insert_money(self, amount):
"""Insert money into the vending machine."""
if amount > 0:
self.balance += amount
print(f"Inserted ${amount:.2f}. Current balance: ${self.balance:.2f}")
else:
print("Please insert a valid amount.")
def select_product(self, code):
"""Select a product and dispense it if enough money is inserted."""
if code in self.products:
product = self.products[code]
if self.balance >= product["price"]:
self.balance -= product["price"]
print(f"Dispensing {product['name']}...")
self.return_change()
else:
print(f"Insufficient balance! {product['name']} costs ${product['price']:.2f}.")
else:
print("Invalid product code.")
def return_change(self):
"""Return any remaining change to the user."""
if self.balance > 0:
print(f"Returning change: ${self.balance:.2f}")
self.balance = 0.0
else:
print("No change to return.")
# Creating a VendingMachine object
machine = VendingMachine()
# Using the vending machine
machine.display_products()
machine.insert_money(2.00)
machine.select_product("A2") # Buying Chips
Available Products:
A1: Soda - $1.50
A2: Chips - $2.00
A3: Candy - $1.00
Inserted $2.00. Current balance: $2.00
Dispensing Chips...
No change to return.
VendingMachine
classdisplay_products()
methodinsert_money()
methodselect_product()
methodreturn_change()
method✅ Encapsulation: Keeps balance management secure.
✅ Code Reusability: Easily modify or add new products.
✅ Scalability: Extend features like multiple payment options.
This example shows real-world OOP implementation, making the vending machine modular, reusable, and efficient! 🚀