Python OOPs Concepts
Class
A class in Python is a blueprint for creating objects. It defines a set of attributes and
methods that the created objects will have. Classes help in organizing code and support
object-oriented programming principles.
Examples
class Dog:
pass
class Person:
def __init__(self, name):
self.name = name
class Car:
wheels = 4
class Student:
def study(self):
print("Studying")
class Rectangle:
def area(self, length, breadth):
return length * breadth
Objects
An object is an instance of a class. It represents a specific implementation of the class
blueprint and has actual values instead of variables. Each object can have different
attributes and states.
Examples
dog1 = Dog()
person1 = Person("Alice")
car1 = Car()
student1 = Student()
rect = Rectangle()
print(rect.area(5, 6))
Inheritance
Inheritance allows a class to inherit attributes and methods from another class. The class
that is inherited from is called the parent class, and the one that inherits is the child class. It
helps in code reusability.
Examples
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
pass
class Vehicle:
def start(self):
print("Starting")
class Car(Vehicle):
def drive(self):
print("Driving")
class A:
def show(self):
print("A")
class B(A):
def display(self):
print("B")
class Parent:
def greet(self):
print("Hello")
class Child(Parent):
pass
class Shape:
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * r * r
Polymorphism
Polymorphism means having many forms. It allows methods to do different things based on
the object it is acting upon. Python achieves polymorphism through method overriding and
duck typing.
Examples
class Cat:
def speak(self):
print("Meow")
class Dog:
def speak(self):
print("Bark")
def animal_sound(animal):
animal.speak()
class Bird:
def fly(self):
print("Flying")
class Airplane:
def fly(self):
print("Flying in air")
for animal in (Cat(), Dog()):
animal.speak()
class Base:
def draw(self):
print("Drawing")
class Circle(Base):
def draw(self):
print("Drawing Circle")