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

Unit_4_OOP_in_Python

The document provides an overview of object-oriented programming (OOP) concepts in Python, including encapsulation, inheritance, abstraction, and polymorphism. It explains how to define classes and create objects, as well as the use of constructors, method overloading, and method overriding. Additionally, it covers data hiding and different types of inheritance, such as single, multiple, and multilevel inheritance.

Uploaded by

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

Unit_4_OOP_in_Python

The document provides an overview of object-oriented programming (OOP) concepts in Python, including encapsulation, inheritance, abstraction, and polymorphism. It explains how to define classes and create objects, as well as the use of constructors, method overloading, and method overriding. Additionally, it covers data hiding and different types of inheritance, such as single, multiple, and multilevel inheritance.

Uploaded by

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

Unit 4

 Object-oriented programming in Python involves creating classes as blueprints for


objects. These objects contain data and the methods needed to manipulate that data.
 The four key concepts of OOP in Python are encapsulation, inheritance, abstraction, and
polymorphism
 Abstraction focuses on hiding implementation details and exposing only the essential
functionality of an object.
 Encapsulation allows you to bundle data (attributes) and behaviors (methods) within a
class to create a cohesive unit.
 Inheritance enables the creation of hierarchical relationships between classes, allowing a
subclass to inherit attributes and methods from a parent class. This promotes code reuse
and reduces duplication.
 Polymorphism allows you to treat objects of different types as instances of the same base
type, as long as they implement a common interface or behavior.

Python Classes and Objects:

1. Define Python Class:


Class ClassName:
# class definition

2. Creating Python Objects:


objectName = ClassName()

Example:
# define a class
class Bike:
name = ""
gear = 0
# create object of class
bike1 = Bike()
# access attributes and assign new values
bike1.gear = 11
bike1.name = "Mountain Bike"
print(f"Name: {bike1.name}, Gears: {bike1.gear} ")

3. Python Methods: We can also define a function inside a Python class. A Python
function defined inside a class is called a method.
Example: (Practical no 17)
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", self.length * self.breadth)

# create object of Room class


study_room = Room()
# assign values to all the properties
study_room.length = 42.5
study_room.breadth = 30.8
# access method inside class
study_room.calculate_area()

4. Python Constructors: Constructors are generally used for instantiating an object. The
task of constructors is to initialize(assign values) to the data members of the class when
an object of the class is created. In Python, the __init__() method is called the constructor
and is always called when an object is created.
In Python, there are two types of constructors:
i)Default Constructor: A default constructor is a constructor that takes no arguments. It is
used to create an object with default values for its attributes.
Example:
class Person:
def __init__(self):
self.name = "John"
self.age = 30

person1 = Person()
print(person1.name)
print(person1.age)

ii)Parameterized Constructor: A parameterized constructor is a constructor that takes one


or more arguments. It is used to create an object with custom values for its attributes.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 25)
print(person.name)
print(person.age)

iii)Constructor Overloading in Python: Constructor overloading involves defining


multiple constructors within a class, each taking a different set of parameters. While
Python does not support explicit constructor overloading like some other languages,
developers can achieve a similar effect by using default values and optional parameters.
Example: (Practical no 18)
class Rectangle:
def __init__(self, length=1, breadth=1):
self.length = length
self.breadth = breadth

# Creating objects with different number of arguments


rect1 = Rectangle()
print(rect1.length, rect1.breadth)

rect2 = Rectangle(5)
print(rect2.length, rect2.breadth)

rect3 = Rectangle(5, 10)


print(rect3.length, rect3.breadth)

5. Method Overloading & Method Overriding in Python:


i) Method Overloading: It is a type of Compile-time Polymorphism using which we
can define two or more methods in the same class with the same name but with a
different parameter list. To overload a method in Python, we need to write the method
logic in such a way that depending upon the parameters passed, a different piece of
code executes inside the function.
Example: (Practical no 19)
class Student:
def hello(self, name=None):
if name is not None:
print('Hey ' + name)
else:
print('Hey ')
# Creating a class instance
std = Student()
# Call the method
std.hello()
# Call the method and pass a parameter
std.hello('Vaibhav')
ii) Method Overriding: It is a type of Run-time Polymorphism. A child class method
overrides (or provides its implementation) the parent class method of the same name,
parameters, and return type. It is used to over-write (redefine) a parent class method
in the derived class.
Example: (Practical no 19)
class Employee:
def message(self):
print('This message is from Employee Class')

class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')

emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()

6. Data Hiding in Python: Data hiding is a method used in object-oriented programming


(OOP) to hide the details of an object and function. Or in other words, data hiding means
isolating the client from the implementation part of the application. Thus, data hiding is
the most essential feature because it avoids dependency and provides security. Data
hiding is also known as information hiding or encapsulation.

Syntax: In python, if we want to hide any variable, then we have to use the double
underscore() before the variable name. This makes the class members inaccessible and
private to other classes.
__variablename

Public: When a member of a class is "public," it means it can be accessed by other


objects. Or in other words, it can be accessed from any part of the program but only
within a program. All the members and member functions are public by default.

Private: When members of the class are private, they can only be accessed by objects of
the same class. It is not accessible outside of the class, not even any child class can access
it. If you try to do it, the Python compiler will give an error message. We use double
underscores (__) before the data member to create a private data member inside the class.

Protected: Protected means the member of a class is only accessible by its inherited or
child class. To create a protected data member inside the class, we use a single
underscore (_) before the data member.

Example 1: (Practical no 20)

class Authentication:
__username = 'abc' # Private member
_password = 'xyz@123' # Protected member

def creden(self):
print("Username:", self.__username)
print("Password:", self._password)

p = Authentication()
p.creden()

Example 2: If we try to access a private member of a class from outside of a class, then it
will throw an error
class Authentication:
__username = 'abc' # Private member
__password = 'xyz@123' # Private member

def creden(self):
print("Username:", self.__username)
print("Password:", self.__password)

p = Authentication()
print("Username:", self.__username) # Accessing from outside of the class
print("Password:", self.__password)

7. Inheritance in Python: Being an object-oriented language, Python supports class


inheritance. It allows us to create a new class from an existing one. The newly created
class is known as the subclass (child or derived class). The existing class from which the
child class inherits is known as the superclass (parent or base class).
Syntax:
# define a superclass
class super_class:
# attributes and method definition

class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class

a) Single Inheritance: In single inheritance, the child class acquires the properties and
can access all the data members and functions defined in the parent class. A child class
can also provide its specific implementation to the functions of the parent class.
Syntax:
class BaseClass1:
#Body of base class
class DerivedClass(BaseClass1):
#body of derived – class

Example 1: (Practical no 21)

# Parent class created


class Parent:
parentname = ""
childname = ""
def show_parent(self):
print(self.parentname)

# Child class created inherits Parent class


class Child(Parent):
def show_child(self):
print(self.childname)

ch1 = Child() # Object of Child class


ch1.parentname = "Vijay" # Access Parent class attributes
ch1.childname = "Parth"
ch1.show_parent() # Access Parent class method
ch1.show_child() # Access Child class method

b) Multiple inheritance: Python provides us the flexibility to inherit multiple base


classes in the child class. Multiple Inheritance means that you're inheriting the property
of multiple classes into one. In case you have two classes, say A and B, and you want to
create a new class which inherits the properties of both A and B.
Syntax:
class A:
# variable of class A
# functions of class A
class B:
# variable of class B
# functions of class B
class C(A, B):
# class C inheriting property of both class A and B
# add more properties to class C

Example 2: (Practical no 21)


class Add:
def Addition(self,a,b):
return a+b;

class Mul:
def Multiplication(self,a,b):
return a*b;

class Derived(Add,Mul):
def Divide(self,a,b):
return a/b;

d = Derived()
print(d.Addition(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

c) Multilevel inheritance: Multilevel Inheritance in Python is a type of Inheritance in


which a class inherits from a class, which itself inherits from another class. It allows a
class to inherit properties and methods from multiple parent classes, forming a hierarchy
similar to a family tree.
Syntax:
class A:
# variable of class A
# functions of class A
class B(A):
# class B inheriting property of class A
# add more properties to class B
class C(B):
# class C inheriting property of class A & B
# add more properties to class C

Example 3: (Practical no 21)


# GrandParent class created
class GrandParent:
grandparentname = ""
def show_grandparent(self):
print(self.grandparentname)

# Parent class created


class Parent(GrandParent):
parentname = ""
childname = ""
def show_parent(self):
print(self.parentname)

# Child class created inherits Parent class


class Child(Parent):
def show_child(self):
print(self.childname)

ch1 = Child() # Object of Child class


ch1.grandparentname = "Vaibhav" # Access GrandParent class attributes
ch1.parentname = "Vijay" # Access Parent class attributes
ch1.childname = "Parth"

ch1.show_grandparent() # Access GrandParent class method


ch1.show_parent() # Access Parent class method
ch1.show_child() # Access Child class method

You might also like