0% found this document useful (0 votes)
29 views9 pages

Experiment 5-PY

The document discusses object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism, abstraction and interfaces. It provides theory explanations and examples to demonstrate each concept.
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)
29 views9 pages

Experiment 5-PY

The document discusses object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism, abstraction and interfaces. It provides theory explanations and examples to demonstrate each concept.
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/ 9

Experiment 5: OOP in Python

AIM: To implement programs based on Classes and Objects, Inheritance,


Polymorphism & Abstraction.

THEORY:

CLASSES: A class is a user-defined blueprint or prototype from which objects are


created. Class creates a user-defined data structure, which holds its own data members
and member functions, which can be accessed and used by creating an instance of that
class. A class is like a blueprint for an object.
Classes are created by keyword class. Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator.

Syntax-
class ClassName:
# class definition
Example-
class Bike:
name = ""
gear = 0

OBJECTS: An Object is an instance of a Class. A class is like a blueprint while an


instance is a copy of the class with actual values.

Syntax-
objectName = ClassName()
Example-
bike1 = Bike()

1. Python program to create and list of employees using Employee class. Program should
also print total number of employees.
Employee class should have:
● Empcount (class variable)
● Id and name (instance variables)
● constructor to set id
● set_name(), get_name() & get_id() methods (instance methods)
● set_emp_count() (class method)
CODE:
class Employee:
#class variable
empcount=0

def __init__(self, eid):


self.eid=eid

@classmethod
def set_empcount(cls):
cls.empcount+=1

def setname(self,name):
self.name=name

def getname(self):
return self.name

def getid(self):
return self.eid

n=int(input("Enter the total number of Employees:"))


L=[ ]
for i in range(n):
id=int(input("Enter Employee ID: "))
name= input("Enter Employee name: ")
e=Employee(id)
e.setname(name)
L.append(e)

for i in L:
print("\n Employee Id:",i.getid(),"\t Employee Name:",i.getname())

OUTPUT:

THEORY:
INHERITANCE: One of the core concepts in object-oriented programming (OOP)
languages is inheritance. It is a mechanism that allows you to create a hierarchy of
classes that share a set of properties and methods by deriving a class from another class.
● Single inheritance: When a child class inherits from only one parent class, it is
called single inheritance.
● Multiple inheritances: When a child class inherits from multiple parent classes, it is
called multiple inheritances.

Syntax-
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}

MRO: In python, method resolution order (MRO) defines the order in which the base
classes are searched when executing a method. First, the method or attribute is searched
within a class and then it follows the order we specified while inheriting. This order is also
called Linearization of a class and set of rules are called MRO(Method Resolution Order).
While inheriting from another class, the interpreter needs a way to resolve the methods
that are being called via an instance. Thus we need the method resolution order. Using
super() accesses the next class in the MRO.
Three principles of MRO:
1. Search for the subclass before going for its baseclass.
2. If a class is inherited from several classes, it searches in the order from left to right.
3. It will not visit any class more than once

Example:
class A:
def __init__(self):
print("A")
super().__init__()

class B:
def __init__(self):
print("B")
super().__init__()
class C(object):
def __init__(self):
print("C")
super().__init__()
class X(A,B):
def __init__(self):
print("X")
super().__init__()

class Y(B,C):
def __init__(self):
print("Y")
super().__init__()

class P(X,Y,C):
def __init__(self):
print("P")
super().__init__()

pobj=P()

Therefore, MRO: P, X, A, Y, B, C.

2. Python Program to demonstrate Multiple Inheritance.

CODE:
class Employee:

def __init__(self, eid,college):


self.eid=eid
super().__init__(college)

def setname(self,name):
self.name=name

def getname(self):
return self.name

def getid(self):
return self.eid

class Student:
def __init__(self,college):
self.college=college

def getcollege(self):
return self.college

class Intern (Employee,Student):


def __init__(self,eid,college,period):
self.period=period
super().__init__(eid,college)

def setdetails(self,name):
self.name=name

def getdetails(self):
print("\n E_id:",super().getid(),"\t Name:",super().getname(),"\t
College:",super().getcollege(),"\t Period:",self.period)

#main prog

eid=int(input("Enter employee Id: "))


college=input("enter college: ")
name=input("enter name")
period=input("enter period of internship")

intern=Intern(eid,college,period)
intern.setdetails(name)
intern.getdetails()

OUTPUT:

THEORY:

POLYMORPHISM: In programming, polymorphism means the same function name (but


different signatures) being used for different types. The key difference is the data types
and number of arguments used in the function.
There are four ways of implementing Polymorphism in Python:
(i) Duck Typing: Duck typing is a concept that says that the “type” of the object is a
matter of concern only at runtime and you don’t need to explicitly mention the type of the
object before you perform any kind of operation on that object, unlike normal typing where
the suitability of an object is determined by its type.

(ii) Method Overloading: By default, Python does not support method overloading, but
we can achieve it by modifying out methods.
Given a single function sum (), the number of parameters can be specified by you. This
process of calling the same method in different ways is called method overloading.

(iii) Operator Overloading: Operator overloading in Python is the ability of a single


operator to perform more than one operation based on the class (type) of operands. So,
basically defining methods for operators is known as operator overloading. For e.g: To
use the + operator with custom objects you need to define a method called __add__.
We know + operator is used for adding numbers and at the same time to concatenate
strings. It is possible because the + operator is overloaded by both int class and str class.
The operators are actually methods defined in respective classes.

(iv) Method Overriding: By using method overriding a class may “copy” another class,
avoiding duplicated code, and at the same time enhance or customize a part of it. Method
overriding is thus a part of the inheritance mechanism.
In Python, method overriding occurs by simply defining the child class in a method with
the same name as a method in the parent class.

3. Python program to overload greater than (>) operator to make it act on user-defined
class objects.

CODE:

class Age:
def __init__(self, years):
self.years = years

def __gt__(self, other):


return self.years > other.years
# create some Age objects
age1 = Age(25)
age2 = Age(30)

# compare them using the greater than operator


if age1 > age2:
print("age1 is greater than age2")
else:
print("age1 is not greater than age2")

# create another Age object and compare it to the first one


age3 = Age(20)

if age1 > age3:


print("age1 is greater than age3")
else:
print("age1 is not greater than age3")

output :

age1 is not greater than age2


age1 is greater than age3

THEORY:

ABSTRACTION: A class that contains one or more abstract methods is called an abstract
class. An abstract method is a method that has a declaration but does not have an
implementation. While we are designing large functional units we use an abstract class.
When we want to provide a common interface for different implementations of a
component, we use an abstract class.
INTERFACES: An interface acts as a template for designing classes. Interfaces also
define methods the same as classes, but abstract methods, whereas class contains
nonabstract methods. Abstract methods are those methods without implementation or
which are without the body. So the interface just defines the abstract method without
implementation. The implementation of these abstract methods is defined by classes that
implement an interface.

Syntax-
An ABC is a simple interface or base class defined as an abstract class in nature, and the
abstract class has certain abstract methods. Following that, if any classes or objects
implement or drive from these base classes, these derived classes are required to
implement all of those methods.
import abc

class Boat(abc.ABC):
@abc.abstractmethod
def swim(self):
pass

4. Python program to demonstrate concept of Interfaces.


The program contains Printer interface and its subclasses to text to any printer.

CODE:

from abc import *


class Printer(ABC):
@abstractmethod
def printit(self,text):
pass

@abstractmethod
def disconnect(self):
pass
class IBM(Printer):
def printit(self,text):
print(text, " to IBM. ")
def disconnect(self):
print("Disconnected from IBM")

class HP(Printer):
def printit(self,text):
print(text, " to HP. ")
def disconnect(self):
print("Disconnected from HP")

#main prog

text="Connescted"

i=int(input("Enter the server of your choice: \n 1.IBM \t 2.HP \n"))


if (i==1):
ibm=IBM()
ibm.printit(text)
elif(i==2):
hp=HP()
hp.printit(text)
opt=input("\nDo you want to disconnect : Y/n")
if (opt=="Y" or opt=="y"):
if (i==1):
ibm.disconnect()
if (i==2):
hp.disconnect()

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy