0% found this document useful (0 votes)
14 views

Slides For Python

slides

Uploaded by

Shubham Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Slides For Python

slides

Uploaded by

Shubham Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Object oriented programming

in Python

Sukrit Gupta and Nitin Auluck

March 20, 2024

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 1/31
Outline

1 An example from the last class

2 Classes and objects around us

3 Inheritance

4 Polymorphism

5 Queues and stacks

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 2/31
Acknowledgement and disclaimer
All mistakes (if any) are ours.
We have used several other sources, which we have referred to in the
appropriate places.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 3/31
Section 1

An example from the last class

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 4/31
What is this?

l = list('Python')

What do you see here in terms of classes/objects?

Ultimately the list class hides away the details of what is going in the
background for the object l.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 5/31
This is a very powerful concept. The object l can now invoke several
methods that are defined in the list class.

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/she wants to use.

This concept is called - abstraction. Makes the life of users easy.

Think of ease of use while interacting with an operating system - (a)


turning on your machine, (b) file copy paste, (c) starting an app, (d)
closing an app.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 6/31
Section 2

Classes and objects around us

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 7/31
An example of classes and objects around us

I was thinking of more examples of classes and objects around us,


while sitting in my office.
Then it occurred to me that my own office is also an example of an
object. How?
We have a class, say: office, which has attributes like: room
number, occupied, person using it, whiteboard installed,
pinboard installed, and so on.
All the individual offices can be instantiated as objects of the class
office, for example - Nitin’s office, Sukrit’s office.
Lets see the code for this: filename - Room1.py.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 8/31
Just to code this up:
class office():
def __init__(shellfish, room_num, occ, name_occupant, wb, pb):
shellfish.room_number = room_num
shellfish.occupied = occ
shellfish.person = None
if shellfish.occupied:
shellfish.person = name_occupant
shellfish.whiteboard_installed = wb
shellfish.pinboard_installed = pb
def print_office_info(shellfish):
print('Room Number: ', shellfish.room_number,
'Occupation status: ', shellfish.occupied,
'Occupied by: ', shellfish.person,
'Whiteboard Installed:', shellfish.whiteboard_installed,
'Pinboard Installed:', shellfish.pinboard_installed)

R1 = office('316', True, 'Sukrit Gupta', 1, 1) #Object: R1


R1.print_office_info()
R2 = office('111', True, 'Nitin Auluck', 0, 0) #Object: R2
R2.print_office_info()
Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 9/31
While we are talking about offices ...
Offices are just one type of the rooms on campus.

What are some other types of rooms on campus?

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.

This property is known as inheritance. Do we see inheritance around


us?

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 10/31
Examples of Inheritance around us.

Cars?

What are some other examples that you can think about?

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 11/31
Section 3

Inheritance

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 12/31
Inheritance
Inheritance is the capability of one class to derive or inherit the
properties (data + functions) from another class.

class subclass_name (superclass_name)

The benefits of inheritance are:

It represents real-world relationships well.


It provides reusability of a code.
It is transitive in nature, which means that if class B inherits from
another class A, then all the subclasses of B would automatically
inherit from class A.
Lets look at a simple example, to begin with. Filenames -
Inheritance.py.
Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 13/31
Inheritance in Python

class Parent():
def show(self):
print("Inside Parent class")

class Child(Parent):
def display(self):
print("Inside Child class")

obj = Child()
obj.display()

obj.show() # Calling Parent class

Next, let’s try to code up our earlier room class example, using
inheritance.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 14/31
Our room example

Open Example 1 (file: example 1 7.1.py).

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 15/31
Another Example (Points & Rectangles)
Let us look at another example of class inheritance.

Recall the class Point program discussed earlier.

Let us implement a class Rectangle. What attributes do we use to


specify the location and size of a rectangle?

For simplicity, assume that the rectangle is either vertical or horizontal


(no angle).

We specify one corner (lower left) of the rectangle, its width, and its
height.

What can be the data types of these three attributes?

Lets see the code for this, filename: Points Rectangles.py.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 16/31
Multiple inheritance

When a child class inherits from multiple parent classes, it is called


multiple inheritance.

This allows the child class to get access to member variables and
member functions of multiple parent classes.

Python supports multiple inheritance. We specify all parent classes as


a comma-separated list in the parentheses.
Open Example (file: example_multiple_inheritance_7.1.py)
Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 17/31
Multilevel Inheritance

When we want to have a multilevel relationship between classes.

Open Example (file: example_multilevel_inheritance_7.1.py)

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 18/31
Section 4

Polymorphism

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 19/31
What does the word polymorphism mean?

Made up of the words ‘poly’ and ‘morph’. Dictionary definition: The


quality or state of existing in or assuming different forms.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 20/31
Polymorphism in Python

Python implements polymorphism by method overriding. Method


overriding is an ability of any OOP language that allows a subclass to
provide a specific implementation of a method that is already provided
by one of its super-class(es).

Method overriding can be used to implement polymorphism in Python.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 21/31
Example: Method Overriding

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()

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 22/31
Example: Method Overriding

Open Example 2 (file: example_2_7.1.py)

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 23/31
Section 5

Queues and stacks

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 24/31
Queue

1
Figure: Analogous to people lining up to wait for goods or services.

Collection of ordered entities that can be modified by the addition of


entities to the back and removal of entities from the front.

A queue is a first-in-first-out (FIFO) data structure. The first element


added to the queue will be the first one to be removed.

enqueue: adding an element to the back of the queue, and


dequeue: removing an element from the front.
1
Source: Wikipedia user:Vegpuff
Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 25/31
Implementing queues using Python
Open Example (file: example_queue_7.1.py)

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]

List functions:
https://docs.python.org/3/tutorial/datastructures.html

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 26/31
Stack

2
Figure: Analogous to a set of physical items stacked on top of each other.

An abstract data type that serves as a collection of elements where


you can push (insert) an element to the stack and pop (remove) an
element from the stack.
Makes it easy to take an item off the top of the stack, while getting
to an item deeper may require taking off multiple other items first.
A stack is a last-in-first-out (LIFO) data structure. The last
element added to the stack will be the first one to be removed.

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 27/31
Implementing stacks using Python

Open Example (file: example_stack_7.1.py)

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]

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 28/31
Do you notice something?

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)

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 29/31
What did we learn today?

1 An example from the last class

2 Classes and objects around us

3 Inheritance

4 Polymorphism

5 Queues and stacks

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 30/31
Thank you!

Sukrit Gupta and Nitin Auluck Intro to Computing and Data Structures 31/31

You might also like