Object-Oriented Programming (OOP)
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.
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 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 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).
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 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 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.
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))