Principle of Oops in Python
Principle of Oops in Python
concept of "objects," which can contain both data (attributes) and behavior
(methods). In Python, OOP is implemented by defining classes that represent
objects and their interactions. The key principles of OOP are:
1 Encapsulation
The feature of wrapping up data (attributes) and methods associated
with that data into a single unit is called encapsulation in Python.
Encapsulation in Python is a fundamental concept in object-oriented
programming (OOP) where you restrict access to certain components of an
object. This is done to protect the object's integrity by hiding its internal
data, exposing only what is necessary. Python achieves this through class
methods and attributes, and by controlling their visibility using public,
private, and protected access specifiers.
Key Terms:
Public: Accessible from anywhere.
Protected: Prefixed with a single underscore _, intended for internal
use but still accessible.
Private: Prefixed with a double underscore __, not directly accessible
outside the class
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project
# method
# to display employee's details
def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
# method
def work(self):
print(self.name, 'is working on', self.project)
Method Overriding
We can provide some specific implementation of the parent class method in our
child class. When the parent class method is defined in the child class with some
specific implementation, then the concept is called method overriding. We may
need to perform method overriding in the scenario where the different definition
of a parent class method is needed in the child class.
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Explanation:
1. Class Animal:
o It has a method speak() that prints "speaking".
2. Class Dog:
o It inherits from the Animal class and overrides the speak() method
to print "Barking" instead of "speaking".
3. Object d:
o When you create an object of class Dog (d = Dog()), and call
d.speak(), the overridden method in the Dog class is called, so it
prints "Barking".
3. Polymorphism
Polymorphism allows methods to have the same name but behave differently
depending on the object or data they are working on. In Python, this is often
achieved through method overriding or having multiple classes with methods of
the same name that behave differently.
Method Overriding: The child class redefines a method from the parent
class.
class Animal:
def sound(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
# Both Dog and Cat classes have the same method name but different behaviors
animals = [Dog(), Cat()]
for animal in animals:
print(animal.sound()) # Outputs: Bark, Meow
4. Abstraction
Abstraction means hiding the complexity and only exposing the essential
features of an object. In Python, abstraction can be achieved by creating abstract
classes or interfaces using the abc (Abstract Base Class) module.
Abstract classes cannot be instantiated and are meant to be subclassed.
Example:
from abc import ABC, abstractmethod
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
Explination
Abstraction:
Shape class: This is an abstract class (defined by inheriting from ABC).
It has an abstract method area() which must be implemented by any class
that inherits from it. This ensures that every shape class has an area()
method, even though the calculation for the area depends on the specific
shape.
The Shape class also has a get_name() method that returns the name of
the shape, which is stored as a private attribute.
Example 2
from abc import ABC, abstractmethod
# Abstract class
class Shape(ABC):
@abstractmethod
def area(self):
pass # Abstract method, no implementation
# Concrete class
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width # Implementation of the area method
# Creating an instance of Rectangle
rect = Rectangle(5, 3)
# Calling the area method and printing the result
print(rect.area()) # Output: 15
Explanation:
1. Abstract Class (Shape):
o The Shape class is an abstract class with an abstract method
area(). This means that any subclass of Shape must implement
the area() method.
2. Concrete Class (Rectangle):
o Rectangle is a subclass of Shape and provides the required
implementation for the area() method.
o The constructor (__init__) initializes the length and width of
the rectangle.
o The area() method computes and returns the area of the
rectangle using the formula length * width.
3. Usage:
o We create a Rectangle object with a length of 5 and a width of.
o We then call the area() method on the rect object, which
returns the area (5 * 3 = 15).