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

Session5 Notes-1

The document discusses Python object-oriented programming concepts like inheritance, polymorphism, encapsulation, abstraction, magic methods and special methods. It provides code examples to demonstrate how these concepts work in Python.

Uploaded by

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

Session5 Notes-1

The document discusses Python object-oriented programming concepts like inheritance, polymorphism, encapsulation, abstraction, magic methods and special methods. It provides code examples to demonstrate how these concepts work in Python.

Uploaded by

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

Inheritance

# Python code to demonstrate how parent constructors are called.

# parent class
class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber

def display(self):
print(self.name)
print(self.idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))

# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance


a = Employee('Sanath', 10012, 30000, "SDE")

# calling a function of the class Person using


# its instance
a.display()
a.details()

-----------------------------------------------------------------------------------
----------

1) Inheritance
# parent class
class Person:

def __init__(self):
self.id = 0
self.firstName = ''
self.lastName = ''

def setAttr(self):
print("Enter Id:")
self.id = int(input())
print("Enter First Name")
self.firstName = input()
print("Enter Last Name")
self.lastName = input()

def getAttr(self):
print(f"Id: {self.id}")
print(f"First Name: {self.firstName}")
print(f"Last Name: {self.lastName}")

class Employee(Person):
def __init__(self):
self.salary = 0
self.location = ''
Person.__init__(self)
super().__init__()

def setDetails(self):
self.setAttr()
print("Enter Salary")
self.salary = int(input())
print("Enter Location")
self.location = input()

def getDetails(self):
self.getAttr()
print(f"Salary: {self.salary}")
print(f"Location: {self.location}")

e1 = Employee()
print("Enter the Employee's Details for E1")
e1.setDetails()
e2 = Employee()
print("Enter the Employee's Details for E2")
e2.setDetails()
print("Get E1's Details")
e1.getDetails()
print("Get E2's Details")
e2.getDetails()

-----------------------------------------------------------------------------------
----------

2) Python Polymorphism
# Parent Class
class Bird:
def msg(self):
print("This is Parent Class")

def fly(self):
print("Most of the birds can fly but some cannot")

class sparrow(Bird):
def fly(self):
print("Sparrow can fly")

class ostrich(Bird):
def fly(self):
print("Ostrich cannot fly")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

print("From Base Class")


obj_bird.msg()
obj_bird.fly()

print("From Sparrow Class - Child")


obj_spr.msg()
obj_spr.fly()

print("From Ostriche Class - Child")


obj_ost.msg()
obj_ost.fly()

-----------------------------------------------------------------------------------
----------

3) Encapsulation in Python
class Base:
def __init__(self):
self.firstName = "Sanath" # Public
self.__firstName = "Palak" # Private

def getPrivateDate(self):
return self.__firstName

class Child(Base):
def __init__(self):
Base.__init__(self)
print("Calling public member of Base Class")
print(self.firstName)
print("Calling Private Member from Base Class")
print(self.getPrivateDate())

c1 = Child()

-----------------------------------------------------------------------------------
----------

4) Abstract in Python - 1

# abstract base class work

from abc import ABC, abstractmethod

class Polygon(ABC):
@abstractmethod
def no_of_sides(self):
pass
class Triangle(Polygon):
# Overriding abstrct method
def no_of_sides(self):
print("I have 3 Sides")

class Pentagon(Polygon):
# Overriding abstrct method
def no_of_sides(self):
print("I have 5 sides")

t1 = Triangle()
t1.no_of_sides()

p1 = Pentagon()
p1.no_of_sides()

-----------------------------------------------------------------------------------
----------
5) Abstract in Python - 2

from abc import ABC, abstractmethod

class Animal(ABC):
@abstractmethod
def move(self):
pass

class Human(Animal):

def move(self):
print("I can walk and run")

class Snake(Animal):

def move(self):
print("I can crawl")

class Dog(Animal):

def move(self):
print("I can bark")

class Lion(Animal):

def move(self):
print("I can roar")

# Driver code
R = Human()
R.move()
K = Snake()
K.move()

R = Dog()
R.move()

K = Lion()
K.move()

-----------------------------------------------------------------------------------
----------

6) Magic Method
# declare our string class
class String:

# magic method to initiate object


def __init__(self, string):
self.string = string

# print our string object


def __repr__(self):
return 'Object: {}'.format(self.string)

def __add__(self, other):


return self.string + other

# Driver Code
if __name__ == '__main__':

# object creation
string1 = String('Hello')

# concatenate a String object and a string


print(string1 +' World')

-----------------------------------------------------------------------------------
----------

7) Magic Method - __add__()

num=10
res = num.__add__(5)
print(res)

-----------------------------------------------------------------------------------
----------

class distance:
def __init__(self, x=None, y=None):
self.ft = x
self.inch = y

def __add__(self, x):


temp = distance()
temp.ft = self.ft+x.ft
temp.inch = self.inch+x.inch
if temp.inch >= 12:
temp.ft += 1
temp.inch -= 12
return temp

def __str__(self):
return 'ft:'+str(self.ft)+' in: '+str(self.inch)

d1 = distance(3, 10)
d2 = distance(4, 4)
print("d1= {} and d2={}".format(d1, d2))

d3 = d1+d2
print(d3)

-----------------------------------------------------------------------------------
----------

8) __repr__

# A simple Person class

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __repr__(self):
rep = 'Person(' + self.name + ',' + str(self.age) + ')'
return rep

# Let's make a Person object and print the results of repr()

person = Person("John", 20)


print(repr(person))

-----------------------------------------------------------------------------------
----------

-> List of Objects - Demo

class Television:
def __init__(self, tv_id=None, name=None, quantity=None):
self.tv_id = tv_id
self.name = name
self.quantity = quantity

class TvStore:
def __init__(self, tv_list):
self.tv_store_name = "Tv Store"
self.tv_list = tv_list

def find_tv_with_min_id(self):
if len(self.tv_list) == 0:
return None
else:
self.tv_list.sort(key = lambda x: x.tv_id)
return self.tv_list[0]

def sort_tv_by_qty(self):
if len(self.tv_list) == 0:
return None
else:
self.tv_list.sort(key=lambda x: x.quantity, reverse=True)
#self.tv_list.sort(key=lambda x: x.quantity)
return self.tv_list

n = int(input("Enter Total Objects: "))


g_tv_list = []
for i in range(n):
tv_id = int(input("Enter Id: "))
name = input("Enter Name: ")
quantity = int(input("Enter Quantity: "))
tv_obj = Television(tv_id, name, quantity)
g_tv_list.append(tv_obj)

tv_store_obj = TvStore(g_tv_list)
if tv_store_obj.find_tv_with_min_id() is None:
print("No Data Found")
else:
tv_min_id = tv_store_obj.find_tv_with_min_id()
print(tv_min_id.tv_id)
print(tv_min_id.name)
print(tv_min_id.quantity)

if tv_store_obj.sort_tv_by_qty() is None:
print("No Data found")
else:
tv_sort_qty = tv_store_obj.sort_tv_by_qty()
"""while size >= 0:
print(tv_sort_qty[size].quantity)
size -= 1"""
"""for item in range(size, -1, -1):
print(tv_sort_qty[item].quantity)"""
for item in tv_sort_qty:
print(item.quantity)

#print(list(range(1, -1, -1)))

You might also like