Lecture 7 OOP1
Lecture 7 OOP1
in Python
Sukrit Gupta
3 Inheritance
4 Polymorphism
l = list([1, 2, 3])
Ultimately the list class hides away the details of what is going in the
background for the object l.
However, the user doesn’t need to know the details of how these
methods are implemented. The user just needs to know how to call a
particular method he wants to use.
Let’s say that besides offices we consider lecture halls and hostel rooms.
Can we say that we have a super class called room and subclasses like
office, lecture hall, hostel room?
The subclasses can have features that are unique to each one of them,
but have some common attributes from the super class.
Cars?
What are some other examples that you can think about?
Inheritance
class Parent():
def show(self):
print("Inside Parent class")
class Child(Parent):
def display(self):
print("Inside Child class")
obj = Child()
obj.display()
Polymorphism
class Parent():
def show(self):
print("Inside Parent class")
class Child(Parent):
def show(self):
print("Inside Child class")
obj1 = Child()
obj1.show()
obj2 = Parent()
obj2.show()
1
Figure: Analogous to people lining up to wait for goods or services.
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def insert_(self, item): #enqueue
self.items.insert(0,item)
def remove(self): #dequeue
return self.items.pop()
def size(self):
return len(self.items)
def peek(self): #return element at the head
return self.items[len(self.items)-1]
2
Figure: Analogous to a set of physical items stacked on top of each other.
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def insert_(self, item): #push
self.items.append(item)
def remove(self): #pop
return self.items.pop()
def size(self):
return len(self.items)
def peek(self): #return element at the top
return self.items[len(self.items)-1]
There was a lot of code that was repeated in the Stack class.
Can we share code between Stack and Queue using inheritance? Show
example (example stack inheritance 7.1.py)
Or better can we write a class from which both Stack and Queue are
inherited? Let’s try.
3 Inheritance
4 Polymorphism