Python is an object-oriented programming (OOP) language, and classes are the blueprint for creating objects. Objects represent real-world entities and encapsulate data (attributes) and behavior (methods).
Why Classes and Objects Are Important
- Encapsulate data and behavior for modular code
- Promote code reuse and maintainability
- Enable inheritance, polymorphism, and abstraction
- Widely used in real-world applications like web apps, games, and data modeling
Example 1: Basic Class and Object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p1 = Person("Alice", 25)
p1.greet()
Output:
Hello, my name is Alice and I am 25 years old.
Example 2: Real-World Scenario – Bank Account
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}, new balance: {self.balance}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"Withdrawn {amount}, new balance: {self.balance}")
else:
print("Insufficient funds")
account = BankAccount("Bob", 1000)
account.deposit(500)
account.withdraw(300)
account.withdraw(1500)
- Demonstrates encapsulation and methods to manage object state
Example 3: Inheritance
class Employee(Person):
def __init__(self, name, age, employee_id):
super().__init__(name, age)
self.employee_id = employee_id
def display_id(self):
print(f"Employee ID: {self.employee_id}")
e1 = Employee("Charlie", 30, "E101")
e1.greet()
e1.display_id()
- Reuse and extend functionality with inheritance
Example 4: Real-World Scenario – Car Class with Methods
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
self.speed = 0
def accelerate(self, value):
self.speed += value
print(f"{self.brand} {self.model} speed: {self.speed} km/h")
def brake(self, value):
self.speed = max(0, self.speed - value)
print(f"{self.brand} {self.model} speed: {self.speed} km/h")
my_car = Car("Toyota", "Corolla")
my_car.accelerate(50)
my_car.brake(20)
- Useful in simulations, games, and real-world object modeling
Best Practices
✔ Keep classes focused on a single responsibility
✔ Use meaningful attribute and method names
✔ Use inheritance and polymorphism to avoid code duplication
✔ Encapsulate data using private or protected attributes
Conclusion
Python classes and objects are the cornerstone of object-oriented programming. Mastering them allows developers to create modular, reusable, and maintainable code for real-world applications like web apps, banking systems, games, and simulations.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/