Python Documentation

Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes in programming. It aims to implement real-world entities like inheritance, polymorphism, encapsulation, etc. in the programming. The main concept of OOP is to bind the data and the functions that work on that together as a single unit so that no other part of the code can access this data.

Classes and Objects

A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods). An object is an instance of a class.

Class Definition Example

class Dog:
def __init__(self, name, age):
ㅤㅤself.name = name
ㅤㅤself.age = age

def bark(self):
ㅤㅤprint(f"{self.name} says: Woof!")

# Creating an object
my_dog = Dog("Buddy", 3)
my_dog.bark()

# Output: Buddy says: Woof!

Inheritance

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).

Inheritance Example

class Animal:
def __init__(self, name):
ㅤㅤself.name = name

def speak(self):
ㅤㅤprint(f"{self.name} makes a sound")

class Dog(Animal):
def speak(self):
ㅤㅤprint(f"{self.name} barks")

dog = Dog("Buddy")
dog.speak()

# Output: Buddy barks

Encapsulation

Encapsulation is the bundling of data with the methods that operate on that data. It restricts direct access to some of an object's components, which is a means of preventing accidental interference and misuse of the methods and data.

Polymorphism

Polymorphism allows us to define methods in the child class with the same name as defined in their parent class. It is the ability of a message to be displayed in more than one form.

Polymorphism Example

class Shape:
def area(self):
ㅤㅤprint("Area of the shape")

class Rectangle(Shape):
def area(self, length, width):
ㅤㅤreturn length * width

class Circle(Shape):
def area(self, radius):
ㅤㅤreturn 3.14 * radius * radius

shape = Shape()
rectangle = Rectangle()
circle = Circle()

shape.area()
print(rectangle.area(5, 3))
print(circle.area(4))