0% found this document useful (0 votes)
12 views7 pages

OOPs Python

The document outlines a practical assignment for a Python programming course, focusing on Object Oriented Programming concepts. It includes tasks such as creating classes for Employee, Student, Hospital, Lion, and SportPerson, demonstrating features like constructors, class variables, operator overloading, and inheritance. Each task is accompanied by Python code examples and expected outputs.
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)
12 views7 pages

OOPs Python

The document outlines a practical assignment for a Python programming course, focusing on Object Oriented Programming concepts. It includes tasks such as creating classes for Employee, Student, Hospital, Lion, and SportPerson, demonstrating features like constructors, class variables, operator overloading, and inheritance. Each task is accompanied by Python code examples and expected outputs.
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

GANPAT UNIVERSITY

U. V. Patel College of Engineering


[Link] CE/IT | Semester IV | 2CEIT404: Python Programming

Practical – 8
Object Oriented Programming
Concepts using Python

Academic Year 2024–25

Q1: Employee Class – Constructor & display()


Create a class Employee with data members: name, department and salary. Use constructor to
initialize values and display() method for printing information of three employees.

Python Code
class Employee:
def __init__(self, name, department, salary):
[Link] = name
[Link] = department
[Link] = salary

def display(self):
print(f'Name : {[Link]}')
print(f'Department : {[Link]}')
print(f'Salary : Rs. {[Link]}')
print('-' * 30)

e1 = Employee('Aarav Shah', 'Engineering', 75000)


e2 = Employee('Priya Mehta', 'Marketing', 62000)
e3 = Employee('Rohan Joshi', 'Finance', 68000)

[Link]()
[Link]()
[Link]()

Output
Name : Aarav Shah
Department : Engineering
Salary : Rs. 75000
------------------------------

Practical-8 | OOPs in Python | Page 1


Name : Priya Mehta
Department : Marketing
Salary : Rs. 62000
------------------------------
Name : Rohan Joshi
Department : Finance
Salary : Rs. 68000
------------------------------

Q2: Student Class – Class Variable & Static Method


Create class Student with instance variables enrollment_no, name, branch; instance methods
get_value() and print_value(); class variable cnt; static method show(). cnt counts instances
created, show() displays its value.

Python Code
class Student:
cnt = 0 # class variable

def __init__(self):
[Link] += 1

def get_value(self, enrollment_no, name, branch):


self.enrollment_no = enrollment_no
[Link] = name
[Link] = branch

def print_value(self):
print(f'Enrollment No : {self.enrollment_no}')
print(f'Name : {[Link]}')
print(f'Branch : {[Link]}')
print('-' * 30)

@staticmethod
def show():
print(f'Total students created: {[Link]}')

s1 = Student()
s1.get_value('21CE001', 'Ananya Patel', 'CE')
s1.print_value()
s2 = Student()
s2.get_value('21IT042', 'Dev Shah', 'IT')
s2.print_value()
[Link]()

Output
Enrollment No : 21CE001
Name : Ananya Patel
Branch : CE
------------------------------
Enrollment No : 21IT042
Name : Dev Shah
Branch : IT
------------------------------
Total students created: 2

Practical-8 | OOPs in Python | Page 2


Q3: Operator Overloading – ** (Exponentiation)
Write a program to overload the ** (exponential) operator using the __pow__() magic method.

Python Code
class Number:
def __init__(self, value):
[Link] = value

def __pow__(self, other):


return Number([Link] ** [Link])

def __str__(self):
return str([Link])

n1 = Number(3)
n2 = Number(4)
result = n1 ** n2
print(f'{n1} ** {n2} = {result}')

n3 = Number(2)
n4 = Number(10)
result2 = n3 ** n4
print(f'{n3} ** {n4} = {result2}')

Output
3 ** 4 = 81
2 ** 10 = 1024

Q4: Hospital Class – getattr, setattr, delattr, hasattr


Create class Hospital with patient_no, patient_name, disease_name. Show use of getattr(), setattr(),
delattr(), hasattr() and display __dict__, __doc__, __name__, __module__, __bases__. Delete
instance p1 in the end.

Python Code
class Hospital:
"""Hospital class for managing patient information."""

def __init__(self, patient_no, patient_name, disease_name):


self.patient_no = patient_no
self.patient_name = patient_name
self.disease_name = disease_name

p1 = Hospital(101, 'Mehul Trivedi', 'Diabetes')

print('getattr:', getattr(p1, 'patient_name'))


setattr(p1, 'disease_name', 'Hypertension')
print('After setattr – disease_name :', p1.disease_name)
print('hasattr patient_no :', hasattr(p1, 'patient_no'))
print('hasattr age :', hasattr(p1, 'age'))
delattr(p1, 'disease_name')
print('hasattr after delattr:', hasattr(p1, 'disease_name'))

print('__dict__ :', p1.__dict__)


print('__doc__ :', Hospital.__doc__)

Practical-8 | OOPs in Python | Page 3


print('__name__ :', Hospital.__name__)
print('__module__ :', Hospital.__module__)
print('__bases__ :', Hospital.__bases__)
del p1
print('Instance p1 deleted.')

Output
getattr: Mehul Trivedi
After setattr – disease_name : Hypertension
hasattr(p1, 'patient_no') : True
hasattr(p1, 'age') : False
After delattr – hasattr(p1, 'disease_name') : False
__dict__ : {'patient_no': 101, 'patient_name': 'Mehul Trivedi'}
__doc__ : Hospital class for managing patient information.
__name__ : Hospital
__module__ : __main__
__bases__ : (<class 'object'>,)
Instance p1 deleted.

Q5: Inheritance – Lion and Cub; Access Modifiers


Design class Lion with roar() and class Cub (inherits Lion) with play(). Define public attribute legs,
protected _ears, private __mane. Show accessibility according to scope using instance simba.

Python Code
class Lion:
def __init__(self):
[Link] = 4 # public
self._ears = 2 # protected
self.__mane = 'golden' # private

def roar(self):
print('Lion roars: ROARRR!')

def show_attributes(self):
print(f' legs (public) : {[Link]}')
print(f' _ears (protected) : {self._ears}')
print(f' __mane (private) : {self.__mane}')

class Cub(Lion):
def play(self):
print('Cub is playing!')

simba = Cub()
[Link]()
[Link]()
print('legs (public) :', [Link])
print('_ears (protected):', simba._ears)
try:
print(simba.__mane)
except AttributeError as e:
print('AttributeError:', e)
print('Name mangling :', simba._Lion__mane)
simba.show_attributes()

Output
Lion roars: ROARRR!

Practical-8 | OOPs in Python | Page 4


Cub is playing!
legs (public) via simba : 4
_ears (protected) via simba : 2
__mane (private) via simba : AttributeError – 'Cub' object has no attribute
'__mane'
__mane via name mangling : golden
legs (public) : 4
_ears (protected) : 2
__mane (private) : golden

Q6: Person & SportPerson – super() vs Parent Class Name


Class Person (name, age) inherited by SportPerson (sport_name). Call parent __init__() using (A)
super() method and (B) parent class name.

Python Code
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print(f'Name : {[Link]} | Age : {[Link]}')

# (A) Using super()


class SportPerson_A(Person):
def __init__(self, name, age, sport_name):
super().__init__(name, age)
self.sport_name = sport_name
def display(self):
super().display()
print(f'Sport: {self.sport_name}')
print('-' * 30)

# (B) Using parent class name


class SportPerson_B(Person):
def __init__(self, name, age, sport_name):
Person.__init__(self, name, age)
self.sport_name = sport_name
def display(self):
[Link](self)
print(f'Sport: {self.sport_name}')
print('-' * 30)

sp1 = SportPerson_A('Virat Kohli', 35, 'Cricket')


[Link]()
sp2 = SportPerson_B('Neeraj Chopra', 26, 'Javelin Throw')
[Link]()

Output
(A) Using super():
Name : Virat Kohli | Age : 35
Sport: Cricket
------------------------------
(B) Using parent class name:
Name : Neeraj Chopra | Age : 26
Sport: Javelin Throw
------------------------------

Practical-8 | OOPs in Python | Page 5


Q7: MRO – Which check() Is Called? (Scenario 1 & 2)
Python uses C3 Linearisation (MRO) to resolve method calls in multiple inheritance. Which check()
is called when E().check() is executed?

Python Code – Scenario 1


# A(check) <- B <- D, C(check) <- D, D <- E
class A_S1:
def check(self): print('Scenario-1: [Link]() called')
class B_S1(A_S1): pass
class C_S1:
def check(self): print('Scenario-1: [Link]() called')
class D_S1(B_S1, C_S1): pass
class E_S1(D_S1): pass

E_S1().check()
print('MRO:', [c.__name__ for c in E_S1.__mro__])

Output – Scenario 1
Scenario-1: [Link]() called
MRO: ['E_S1', 'D_S1', 'B_S1', 'A_S1', 'C_S1', 'object']

Python Code – Scenario 2


# C(check),A(check) <- D; D,B(check) <- E; F(check) standalone
class A_S2:
def check(self): print('Scenario-2: [Link]() called')
class B_S2:
def check(self): print('Scenario-2: [Link]() called')
class C_S2:
def check(self): print('Scenario-2: [Link]() called')
class D_S2(C_S2, A_S2): pass
class E_S2(D_S2, B_S2): pass

E_S2().check()
print('MRO:', [c.__name__ for c in E_S2.__mro__])

Output – Scenario 2
Scenario-2: [Link]() called
MRO: ['E_S2', 'D_S2', 'C_S2', 'A_S2', 'B_S2', 'object']

Q8: Abstract Class – Reptile, Python, Snake


Python and Snake subclasses implement abstract methods crawl() and sting() of superclass
Reptile. Verify using issubclass() and isinstance().

Python Code
from abc import ABC, abstractmethod

class Reptile(ABC):
@abstractmethod
def crawl(self): pass

Practical-8 | OOPs in Python | Page 6


@abstractmethod
def sting(self): pass

class Python(Reptile):
def crawl(self): print('Python is crawling slowly.')
def sting(self): print('Python constricts its prey.')

class Snake(Reptile):
def crawl(self): print('Snake is crawling swiftly.')
def sting(self): print('Snake stings with venom!')

p = Python()
[Link]()
[Link]()
s = Snake()
[Link]()
[Link]()

print('issubclass(Python, Reptile) :', issubclass(Python, Reptile))


print('isinstance(Snake(), Reptile):', isinstance(Snake(), Reptile))

Output
Python is crawling slowly.
Python constricts its prey.
Snake is crawling swiftly.
Snake stings with venom!

issubclass(Python, Reptile) : True


isinstance(Snake(), Reptile): True

Practical-8 | OOPs in Python | Page 7

You might also like