Classes and Objects in Python Explained
Python is one of the easiest and most powerful programming languages, widely used in data science, web development, automation, and AI. While beginners can start quickly with basic syntax, mastering classes and objects is essential to build real-world applications.
Classes and objects are the foundation of Object-Oriented Programming (OOP). They help you organize code, reuse logic, and represent real-world systems in a structured way.
In this guide, you will learn everything from basic concepts to advanced usage, along with complete working code examples.
What is a Class in Python?
A class is a blueprint for creating objects. It defines variables (attributes) and functions (methods).
Basic Class Example
class Car:
color = "Red"
def drive(self):
print("Car is driving")
What is an Object in Python?
An object is an instance of a class.
Object Example
c1 = Car()
c1.drive()
print(c1.color)
Class vs Object (Quick Understanding)
- Class → Blueprint
- Object → Real instance
Example:
- Class = Car design
- Object = Actual car
Constructor in Python (init Method)
The constructor initializes object values.
Complete Example
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print("Name:", self.name)
print("Marks:", self.marks)
s1 = Student("John", 90)
s1.display()
Instance Variables and Methods
Instance variables are unique to each object.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is", self.name)
p1 = Person("Alice", 25)
p1.greet()
Class Variables
Shared among all objects.
Example
class Company:
company_name = "TechCorp"
c1 = Company()
c2 = Company()
print(c1.company_name)
print(c2.company_name)
Types of Methods in Python
1. Instance Method
class Demo:
def show(self):
print("Instance method")
d = Demo()
d.show()
2. Class Method
class Demo:
@classmethod
def show(cls):
print("Class method")
Demo.show()
3. Static Method
class Demo:
@staticmethod
def show():
print("Static method")
Demo.show()
Real-Time Examples (Complete Code)
1. Banking System
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def deposit(self, amount):
self.balance += amount
print("Deposited:", amount)
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print("Withdrawn:", amount)
else:
print("Insufficient balance")
def display(self):
print("Account Holder:", self.name)
print("Balance:", self.balance)
a1 = Account("Ravi", 1000)
a1.deposit(500)
a1.withdraw(300)
a1.display()
2. Student Management System
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def grade(self):
if self.marks >= 90:
return "A"
elif self.marks >= 75:
return "B"
else:
return "C"
def display(self):
print(self.name, self.marks, self.grade())
s1 = Student("Anu", 85)
s1.display()
3. E-commerce Product System
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def discount(self, percent):
self.price -= self.price * percent / 100
def show(self):
print("Product:", self.name)
print("Price:", self.price)
p1 = Product("Laptop", 50000)
p1.discount(10)
p1.show()
Inheritance Example (Advanced)
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.sound()
d.bark()
Encapsulation Example
class Bank:
def __init__(self):
self.__balance = 0
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
b = Bank()
b.deposit(1000)
print(b.get_balance())
Polymorphism Example
class Bird:
def sound(self):
print("Bird sound")
class Sparrow(Bird):
def sound(self):
print("Chirp")
class Crow(Bird):
def sound(self):
print("Caw")
for b in (Sparrow(), Crow()):
b.sound()
Memory Management
Python automatically handles memory using garbage collection, so you don’t need manual memory management.
Best Practices
- Use meaningful class names
- Keep classes simple
- Use constructors properly
- Follow naming conventions
- Avoid unnecessary complexity
Common Mistakes
-
Forgetting
self - Confusing class and object
- Not using constructors
- Writing large classes
Conclusion
Classes and objects are essential for building structured and scalable Python applications.
- Class defines structure
- Object represents real-world data
By practicing the above examples, you can move from beginner to advanced level confidently.
FAQs (SEO Optimized)
What is a class in Python?
A class is a blueprint for creating objects.
What is an object in Python?
An object is an instance of a class.
What is init method?
Constructor used to initialize values.
What is self keyword?
Refers to current object.
What are methods?
Functions inside a class.
What are class variables?
Shared variables across objects.
Why classes are used?
To organize and reuse code.
How to create object?
Using class name.
What is OOP in Python?
Programming using classes and objects.
Where classes are used?
Web apps, AI, automation, etc.
.jpeg)
Comments
Post a Comment