Python is an object-oriented programming (OOP) language, meaning it allows developers to model real-world entities using classes and objects.
- A class is a blueprint for creating objects.
- An object is an instance of a class with specific attributes and behaviors.
Why Use Classes and Objects?
Organizes code into reusable components
Encourages modularity and maintainability
Enables encapsulation, inheritance, and polymorphism
1. Creating Classes and Objects
1.1 Defining a Class
A class is defined using the class
keyword.
class Car:
def __init__(self, brand, model, year): # Constructor
self.brand = brand
self.model = model
self.year = year
def display_info(self): # Method
print(f"{self.year} {self.brand} {self.model}")
# Creating an object (instance)
car1 = Car("Toyota", "Corolla", 2022)
car1.display_info()
Output:
2022 Toyota Corolla
2. Class Components
Component | Description |
---|---|
Attributes | Variables that store object data |
Methods | Functions inside a class that define behavior |
Constructor (__init__ ) | Initializes object attributes |
self | Represents the instance of the class |
3. Instance vs Class Variables
3.1 Instance Variables (Unique to Each Object)
Defined inside __init__()
, belong to each object separately.
class Person:
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
print(p1.name) # Output: Alice
print(p2.age) # Output: 30
3.2 Class Variables (Shared Across Objects)
Defined outside __init__()
, shared by all instances.
class Employee:
company = "TechCorp" # Class variable
def __init__(self, name):
self.name = name # Instance variable
emp1 = Employee("John")
emp2 = Employee("Sarah")
print(emp1.company) # Output: TechCorp
print(emp2.company) # Output: TechCorp
4. Class Methods and Static Methods
4.1 Instance Methods (Operate on Object Data)
class Dog:
def __init__(self, name):
self.name = name
def bark(self): # Instance method
print(f"{self.name} says Woof!")
dog1 = Dog("Buddy")
dog1.bark()
Output:
Buddy says Woof!
4.2 Class Methods (Operate on Class Variables)
class Animal:
species = "Mammal"
@classmethod
def set_species(cls, new_species):
cls.species = new_species
Animal.set_species("Reptile")
print(Animal.species) # Output: Reptile
4.3 Static Methods (Independent of Object or Class)
Static methods donβt access self
or cls
, used for utility functions.
class MathUtils:
@staticmethod
def add(a, b):
return a + b
print(MathUtils.add(5, 3)) # Output: 8
5. Object-Oriented Principles in Python
5.1 Encapsulation (Data Hiding)
Encapsulation restricts access to class attributes using private variables (__var
).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def get_balance(self):
return self.__balance # Getter method
account = BankAccount(1000)
print(account.get_balance()) # Output: 1000
π« account.__balance
is not accessible directly.
5.2 Inheritance (Reusing Code in Child Classes)
Inheritance allows a class to inherit methods and attributes from another class.
class Vehicle:
def __init__(self, brand):
self.brand = brand
def show_brand(self):
print(f"Brand: {self.brand}")
class Car(Vehicle): # Inheriting from Vehicle
def __init__(self, brand, model):
super().__init__(brand) # Call parent constructor
self.model = model
car = Car("Honda", "Civic")
car.show_brand() # Output: Brand: Honda
5.3 Polymorphism (Multiple Forms of a Method)
Method Overriding (Child Class Overrides Parent Method)
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self): # Overriding speak()
print("Bark!")
dog = Dog()
dog.speak() # Output: Bark!
6. Special Methods (Magic Methods / Dunder Methods)
Magic methods (dunder = double underscore) provide operator overloading.
6.1 __str__()
β String Representation of an Object
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self): # Custom string representation
return f"{self.title} by {self.author}"
book = Book("Python Basics", "John Doe")
print(book) # Output: Python Basics by John Doe
6.2 __add__()
β Operator Overloading
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(2, 3)
p2 = Point(4, 5)
result = p1 + p2 # Calls __add__()
print(result.x, result.y) # Output: 6, 8
7. Using isinstance()
and issubclass()
7.1 isinstance()
β Check Object Type
print(isinstance(5, int)) # Output: True
7.2 issubclass()
β Check Class Inheritance
print(issubclass(Car, Vehicle)) # Output: True
8. Real-World Example: Student Management System
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def display(self):
print(f"Student: {self.name}, Grade: {self.grade}")
class School:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def show_students(self):
for student in self.students:
student.display()
s1 = Student("Alice", "A")
s2 = Student("Bob", "B")
school = School()
school.add_student(s1)
school.add_student(s2)
school.show_students()
Output:
Student: Alice, Grade: A
Student: Bob, Grade: B
9. Summary
Concept | Explanation |
---|---|
Class | Blueprint for objects |
Object | Instance of a class |
Attributes | Data stored in an object |
Methods | Functions inside a class |
Encapsulation | Restricting access to data |
Inheritance | Reusing code in child classes |
Polymorphism | Methods behaving differently |
β
Use classes to organize code efficiently.
β
Use objects to create reusable instances.
β
Follow OOP principles for clean, scalable code.