0% found this document useful (0 votes)
3 views8 pages

Principle of Oops in Python

Object-Oriented Programming (OOP) in Python is centered around the use of objects that encapsulate data and behavior, with key principles including encapsulation, inheritance, polymorphism, and abstraction. Encapsulation protects object integrity by restricting access to internal data, while inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables methods to behave differently based on the object, and abstraction focuses on exposing only essential features while hiding complexity.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Principle of Oops in Python

Object-Oriented Programming (OOP) in Python is centered around the use of objects that encapsulate data and behavior, with key principles including encapsulation, inheritance, polymorphism, and abstraction. Encapsulation protects object integrity by restricting access to internal data, while inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables methods to behave differently based on the object, and abstraction focuses on exposing only essential features while hiding complexity.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Object-Oriented Programming (OOP) is a programming paradigm based on the

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)

# creating object of a class


emp = Employee('Ankita', 8000, 'NLP')

# calling public method of the class


emp.show()
emp.work()
2. Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.

Inheritance allows a class (child or subclass) to inherit the attributes and


methods of another class (parent or superclass). This promotes code reuse and
creates a natural hierarchy between related classes.
 The child class can override or extend the behavior of the parent class.

Example: single Inheritance


class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Example:-Multiple Inheritance
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

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 Shape(ABC): # Abstract class


@abstractmethod
def area(self):
pass # Abstract method (no implementation)

class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2

# You can't create an instance of Shape, but you can of Circle


c = Circle(5)
print(c.area()) # Outputs: 78.5

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).

Summary of OOP Principles


1. Encapsulation: Bundle data and methods within classes, hide
implementation details.
2. Inheritance: Create new classes that reuse, extend, or modify behaviors
from existing classes.
3. Polymorphism: Use a common interface for different types, where
methods behave differently.
4. Abstraction: Hide complex implementation details and expose only
essential functionalities.

You might also like