Python is an object-oriented programming (OOP) language, and classes and objects are its core concepts. A class is a blueprint for creating objects, while an object is an instance of a class with its own data and behavior.
Using classes and objects allows you to organize code logically, reuse code, and model real-world problems in your programs.
Why Classes and Objects Are Important
- Encapsulate data and behavior
- Make code reusable and modular
- Enable real-world modeling
- Support inheritance and polymorphism
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Car: {self.brand} {self.model}")
# Creating an object
my_car = Car("Toyota", "Corolla")
my_car.display_info()
Defining a Class in Python
Use the class keyword to define a class.
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")
__init__is a constructor called automatically when an object is createdselfrefers to the instance of the class
Creating Objects (Instances)
person1 = Person("Aman", 25)
person2 = Person("Neha", 22)
person1.greet()
person2.greet()
Accessing Attributes and Methods
print(person1.name) # Access attribute
person1.greet() # Call method
Updating Attributes
person1.age = 26
print(person1.age)
Deleting Attributes and Objects
del person1.age # Delete attribute
del person2 # Delete object
Example: Real-World Scenario
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}, Remaining Balance: {self.balance}")
else:
print("Insufficient balance!")
account = BankAccount("Sagar", 1000)
account.deposit(500)
account.withdraw(200)
account.withdraw(2000)
Best Practices
✔ Keep classes focused on a single responsibility
✔ Use meaningful attribute and method names
✔ Use inheritance and encapsulation wisely
✔ Avoid deep nesting of classes
Conclusion
Classes and objects are fundamental for object-oriented programming in Python. They help in structuring programs efficiently, creating reusable code, and modeling real-world systems.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/