
Exploring Python Classes
In Python, a class is a blueprint for creating objects that possess attributes and behaviors. Classes enable you to model real-world entities in your programs, making your code more organized, reusable, and scalable. Let's delve into Python classes in a beginner-friendly manner.
A class is a user-defined blueprint or prototype for creating objects. It defines the structure and behavior of objects by encapsulating data (attributes) and methods (functions) that operate on the data. Objects are instances of classes, representing specific instances of the entity defined by the class.
You can create a class in Python using the class keyword followed by the class name. Here's a simple example of a class representing a Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def drive(self):
print(f"{self.make} {self.model} is now driving.")
In this example, Car is the class, and make, model, and year are attributes. The __init__ method is a special method called the constructor, used to initialize object attributes. The drive method is a behavior associated with the Car class.
Once a class is defined, you can create objects (instances) of that class using the class name followed by parentheses. Here's how you can create instances of the Car class:
car2 = Car("Honda", "Accord", 2021)
In this example, car1 and car2 are instances of the Car class, each with its own set of attributes.
You can access the attributes and call methods of an object using dot notation. Here's how you can access attributes and call methods of the Car objects:
print(car2.year) # Output: 2021
car1.drive() # Output: Toyota Camry is now driving.
def __init__(self, make, model, year, battery_capacity):
super().__init__(make, model, year)
self.battery_capacity = battery_capacity
def charge(self):
print(f"{self.make} {self.model} is now charging.")
In this example, ElectricCar is a subclass of Car, inheriting its attributes and methods.
1. Bank Account Management:
Q. You are tasked with implementing a simple bank account management system
using Python classes. Create a BankAccount class with attributes
account_number, balance, and methods deposit() and withdraw()
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}")
else:
print("Insufficient funds.")
# Example usage
account1 = BankAccount("123456")
account1.deposit(1000)
account1.withdraw(500)
2. Product Inventory Management:
Q. Develop a product inventory management system using Python classes.
Create a Product class with attributes name, price, and quantity, and
methods add_stock() and sell().
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def add_stock(self, quantity):
self.quantity += quantity
print(f"Added {quantity} units of {self.name} to inventory.")
def sell(self, quantity):
if self.quantity >= quantity:
self.quantity -= quantity
print(f"Sold {quantity} units of {self.name}.")
else:
print("Insufficient stock.")
# Example usage
product1 = Product("Laptop", 999, 10)
product1.add_stock(5)
product1.sell(3)
3. Library Management System:
Q. Implement a library management system using Python classes. Create Book
and Library classes, where each Book object has attributes title, author,
and availability, and the Library class has a method borrow_book() to borrow
a book.
def __init__(self, title, author):
self.title = title
self.author = author
self.availability = True
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def borrow_book(self, title):
for book in self.books:
if book.title == title and book.availability:
book.availability = False
print(f"Borrowed {title}.")
return
print("Book not available.")
# Example usage
library = Library()
book1 = Book("Python Programming", "John Doe")
library.add_book(book1)
library.borrow_book("Python Programming")
4. Vehicle Rental System:
Q. Develop a vehicle rental system using Python classes. Create Vehicle and
Rental classes, where each Vehicle object has attributes model,
rental_price_per_day, and available, and the Rental class has methods
rent_vehicle() and return_vehicle().
def __init__(self, model, rental_price_per_day):
self.model = model
self.rental_price_per_day = rental_price_per_day
self.available = True
class Rental:
def __init__(self):
self.vehicles = []
def add_vehicle(self, vehicle):
self.vehicles.append(vehicle)
def rent_vehicle(self, model):
for vehicle in self.vehicles:
if vehicle.model == model and vehicle.available:
vehicle.available = False
print(f"Rented {model}.")
return
print("Vehicle not available.")
def return_vehicle(self, model):
for vehicle in self.vehicles:
if vehicle.model == model and not vehicle.available:
vehicle.available = True
print(f"Returned {model}.")
return
print("Invalid vehicle.")
# Example usage
rental = Rental()
car1 = Vehicle("Toyota Camry", 50)
rental.add_vehicle(car1)
rental.rent_vehicle("Toyota Camry")
Summary:
Python classes provide a powerful mechanism for modeling real-world entities
and organizing code into reusable components. By defining classes, you can
encapsulate data and behaviors, enabling better code organization,
abstraction, and modularity in your Python programs. Classes play a central
role in object-oriented programming, facilitating code reuse,
maintainability, and scalability.