Unit 4 Object Oriented Programming Chapter 6 (5 August ) Final
Unit 4 Object Oriented Programming Chapter 6 (5 August ) Final
Authors Gopal Gupta, Shelley Gupta, Aatif Jamshed, Anurag Mishra, Harsh
Khatter
Authorized by
Creation/Revision Date May 2021, December 2021
Version 1.0
0
Contents
3. Introduction to collections/sequences data types ............................ Error! Bookmark not defined.
3.1 String ............................................................................................. Error! Bookmark not defined.
3.1.1 Creation of String .................................................................... Error! Bookmark not defined.
3.1.2 Accessing Strings ..................................................................... Error! Bookmark not defined.
3.1.3 Updation / Deletion ................................................................ Error! Bookmark not defined.
3.1.4 Built-In Method ....................................................................... Error! Bookmark not defined.
3.1.5 Basic Operations ..................................................................... Error! Bookmark not defined.
3.1.6 String Formatters .................................................................... Error! Bookmark not defined.
3.1.7 Loop with String ...................................................................... Error! Bookmark not defined.
3.2. List ................................................................................................ Error! Bookmark not defined.
3.2.1. Creation ................................................................................. Error! Bookmark not defined.
3.2.2. Accessing ............................................................................... Error! Bookmark not defined.
3.2.3. Update. .................................................................................. Error! Bookmark not defined.
3.2.4. Built-in method ...................................................................... Error! Bookmark not defined.
3.2.5. Operations with list ................................................................ Error! Bookmark not defined.
3.2.6. Loops ..................................................................................... Error! Bookmark not defined.
3.2.7 Nested List .............................................................................. Error! Bookmark not defined.
3.2.8 List Comprehension ................................................................. Error! Bookmark not defined.
3.3 Tuple ............................................................................................. Error! Bookmark not defined.
3.3.1 Creation of Tuple..................................................................... Error! Bookmark not defined.
3.3.2 Accessing Tuple ....................................................................... Error! Bookmark not defined.
3.3.3 Modification/ Updating a Tuple .............................................. Error! Bookmark not defined.
3.3.4 Built-in Methods in Dictionary................................................. Error! Bookmark not defined.
3.3.5 Operations on Tuple ................................................................ Error! Bookmark not defined.
3.4 Dictionaries ................................................................................... Error! Bookmark not defined.
3.4.1 Creation of Dictionary ............................................................. Error! Bookmark not defined.
3.4.2 Accessing of Dictionary ........................................................... Error! Bookmark not defined.
3.4.3 Modification in Dictionary ....................................................... Error! Bookmark not defined.
3.4.4 Nested Dictionary ................................................................... Error! Bookmark not defined.
1
3.4.5 Built-in Methods in Dictionary................................................. Error! Bookmark not defined.
3.3.6 Loops and conditions on dictionaries....................................... Error! Bookmark not defined.
3.5 Set ................................................................................................. Error! Bookmark not defined.
3.5.1 Creation .................................................................................. Error! Bookmark not defined.
3.5.2 Accessing ................................................................................ Error! Bookmark not defined.
3.5.3 Modification ........................................................................... Error! Bookmark not defined.
3.5.4 Built-in-methods ..................................................................... Error! Bookmark not defined.
3.5.5 Operators ................................................................................ Error! Bookmark not defined.
3.5.6 Loops ...................................................................................... Error! Bookmark not defined.
3.5.7 Frozen Set ............................................................................... Error! Bookmark not defined.
3.6 Summary ....................................................................................... Error! Bookmark not defined.
References: ......................................................................................... Error! Bookmark not defined.
2
Table of Contents
6.1. Introduction to OOPs: ....................................................................................................................6
6.1.1.Definition: ............................................................................................................................7
6.1.2.History of OOPS:...................................................................................................................7
6.2.Requirements of OOPs:...................................................................................................................8
6.2.1.Need of OOPS: .........................................................................................................................8
6.2.2.Why Oops? ..............................................................................................................................9
6.3.Outline of OOPs: .............................................................................................................................9
6.4.Deep-Dive into Programming (let's move towards implementation) ............................................. 15
6.4.1.Basic Terminologies: Class, Object and Instance .................................................................... 15
6.5.Constructor................................................................................................................................... 23
6.5.1 Concept of __new__............................................................................................................... 24
6.5.2. Types of the constructor:....................................................................................................... 26
6.5.3. Default values within the constructor.................................................................................... 27
6.6.Variable ........................................................................................................................................ 27
6.6.1. Types of variables in Python .................................................................................................. 28
6.6.2. How to access instance variables ........................................................................................... 30
6.7.Methods ....................................................................................................................................... 30
6.7.1. Types of methods in Python: ................................................................................................. 30
6.7.1.1.Non-Static Methods / Instance Methods ......................................................................... 30
6.7.1.2.Static Method:................................................................................................................. 32
6.8.Pillars of Oops............................................................................................................................... 32
6.8.1.Inheritance ............................................................................................................................ 32
6.8.1.1.Single inheritance ............................................................................................................ 33
6.8.1.2.Multiple inheritance ........................................................................................................ 33
6.8.1.3.Multilevel inheritance ..................................................................................................... 33
6.8.1.4. Hierarchical inheritance .................................................................................................. 34
6.8.1.5. Hybrid inheritance .......................................................................................................... 35
6.8.2. Inherit Constructor ................................................................................................................ 35
6.8.3. What will happen if our child class has its constructor? ......................................................... 36
3
6.8.4. How to inherit the parent constructor if the child has its constructor? .................................. 36
6.8.5. Method Resolution Order (MRO).......................................................................................... 37
6.8.2.Encapsulation ........................................................................................................................ 40
6.8.1.1.Access Control (Access Modifier) ..................................................................................... 40
6.8.2.2.Protected or Single Underscore[_] ................................................................................... 41
6.8.2.3.Privateor Double Underscores[__] ................................................................................... 41
6.8.3.Abstraction ............................................................................................................................ 43
6.8.3.2. Abstract Method ............................................................................................................ 44
6.8.4.Polymorphism ........................................................................................................................ 45
6.8.4.1.Method overloading ........................................................................................................ 47
6.8.4.2.Method overriding .......................................................................................................... 48
6.8.4.3 Operator overloading ...................................................................................................... 51
6.8.4.4.Special/Dunder/Magic methods ...................................................................................... 53
6.9 Applications of OOPs ................................................................................................................... 56
6.9.1 Stack and its implementation ................................................................................................ 56
6.9.1.1 Introduction to Stack ....................................................................................................... 57
6.9.1.2 Applications of stack........................................................................................................ 57
6.9.1.3 Stack has two main operations ........................................................................................ 58
6.9.1.4 Implementation of Stack ................................................................................................. 58
6.9.2 Queue and its implementation ............................................................................................... 66
6.9.2.1 Introduction to Queue ..................................................................................................... 66
6.9.2.1 Queue Operations ........................................................................................................... 66
6.9.2.3 Implementation of Queue operations .............................................................................. 67
6.9.3 LinkedList and its implementation .......................................................................................... 71
6.9.3.1 Introduction to Linked List ............................................................................................... 71
6.9.3.2 Implementation of Singly Liked List ................................................................................. 71
6.9.3.3 Singly Linked List Attributes and Methods ....................................................................... 72
6.9.3.4 Implementation of Doubly Liked List ............................................................................... 75
6.9.3.5 Doubly Linked List Attributes and Methods ..................................................................... 75
References: ........................................................................................................................................ 79
4
5
UNIT 6
Object-Oriented Programming
6
6.1.1. Definition:
A widely used and popularly known approach that involves designing programs based on class
and its objects. Objects consists of data and code. Data consists of attributes and code consists
of methods.
7
6.2. Requirements of OOPs:
Oops, serve various benefits that empower the developer to make the code more
readable, reusable, ease bug detection, and make programs into modules. The figure 6.2 depicts
the need of migration from structured programming to Object-Oriented programing paradigm.
We have divided the oops' requirement into two parts: ' Need' and 'Why.'
As depicted in figure 6.2 structured programming programs are divided into programs or
functions. It is difficult to modify and reuse structured programs. Thus, object oriented
programming deals with objects consisting of data and functions both, in which it is easy to reuse
the code.
6.2.1.Need of OOPS:
Because only the owner method should access its associated data and no other form should
have access to such data, it is not associated with it. The figure 6.2.1. enumerates the need of
OOPs. Oops, does this for us!!.
8
Figure 6.2.1: Need of OOP
6.2.2.Why Oops?
1. Code Reusability, Readability, Scalability
2. Real World Mapping
3. A Better organization of Data and Methods
4. Efficient Error identification
5. Better access control
The requirement of Oops can be further more understood by reading section 6.3, in which we
have elaborated the topics abstraction, inheritance, data hiding, encapsulation, etc.
9
The figure 6.3 has discussed about real world mapping by an Oops programmer with two classes:
1. Human Class: The human class consists of:
• Data having two attributes age and gender.
• Method are moving (), happy (), standing() and reading().
• Objects: h1, h2, h3, h4, h6.
2. Car Class: The car class consists of:
• Data having attribute color.
• Method are moving (), accelate(), engine_on().
• Objects: Car1 and Car2
When we read and understand the four major concepts of OOP, such as abstraction,
encapsulation, inheritance, and polymorphism, we can better understand OOPs.
10
functionality, we put different items (data) in the other part (classes) of the house, such as Bed
in the bedroom, sofa, TV in the drawing-room, utensils, and stove in the kitchen, soap, shampoo,
buckets in the bathroom, etc. Here, we are trying to bind or place the things as their usages.
We call this concept encapsulation.
Most of the items are accessible to all the house members, but some valuables such as money
and jewelry are kept hidden in the closet, i.e., neither all the house members nor outsiders have
access to them. This is data hiding.
We use various appliances such as TV, Fridge, Fan, AC, etc. Neither do we create them, nor we
have any interest in their internal workings. We operate them, i.e., their inner working is
abstracted from us. This is an abstraction.
let's go through each of these concepts and try to understand them better:
6.3.2. Abstraction
Abstraction is the method of covering the particulars and exposing/showing only the essential
aspects of an idea or entity, omitting any context information or description. Consider an ATM as
a clear example. You are just concerned with getting your money from the ATM; you are
unconcerned with how it is dispatched, stocked, or calculates currency.
Since the most important thing for an ATM is to dispense cash, you can abstract away the
specifics and only show the dispense () method when making an ATM Machine class. There are
several abstraction degrees; as you get further, the abstraction level increases, and some bits of
knowledge decrease. As you lower the level of abstraction, you begin to notice more information.
11
For example, an airplane, a bus, a train, and a ship are all modes of transportation that carry
people at a high altitude, but when you get down to earth, you'll note that an airplane flies, a bus
travels on the ground, a train travels on a railway track, and a ship sail on the sea.
6.3.3. Encapsulation
Encapsulation is similar to abstraction in that it masks implementation data as well, but the goal
is distinct. It keeps implementation specifics hidden from the rest of the world so that you can
modify them later. As depicted in figure 6.3.3. encapsulation is the process of shielding a class's
or object's internal workings from outside powers, making them available only by techniques
such as "getters" and "setters." Encapsulation helps avoid unintended modifications to data and
12
functions within a given class/object from external sources, resulting in serious harm in certain
software parts.
By limiting data access to methods, classes and objects can properly handle change and
determine which external sources can use or modify the data stored within, depending on the
available methods. This eliminates the risk of breaking other code in our software that operates
our specific class or entity, even though we make improvements elsewhere.
Polymorphism is a Greek word that refers to "one name, multiple ways," which is just what the
meaning entails. Inheritance and polymorphism are related in the same way as abstraction and
encapsulation are (and encapsulation).
Polymorphism in OOP allows for various acts to be done based on which entity is executing them.
It defines a trend in which classes use the same interface but have different features.
Build a new subclass named Dog using the Animal superclass and the Bird subclass as an example.
Both dogs and birds make noises, but dogs bark and birds’ chirp. Each subclass will have a Sound
() form, which will yield different results despite being named the same thing. As discussed in
figure 6.3.4. the Sound () method for a dog will bark, the Sound() method for a cat will meow,
and the Sound() method for a lion will roar.
13
Figure 6.3.4: Various types of Sound
6.3.5. Inheritance
14
Parent Class: It contains the attributes and methods common and reusable for the number of
times.
Child Class: It inherits all the attributes and methods that are available in its Python Parent
Class. It also contains its own attributes and methods.
Think about Employee Class: What would be the attributes and methods?
Attributes: emp Id, age, name, hire date, gender, address, salary
Methods: add () ,delete(), update(), salaryhike()
So, you can declare them in the parent class and use them in the child classes. Similarly, some
calculations like the Salary Hike percentage might be the same. We can define
a function/method in the parent class for one time, and you can call it from multiple child classes.
Syntax:
class ParentClass: # parent class
class ChildClass(ParentClass): # some attributes of the child class
15
Class
Class is the way to get organized real-world things into coding. That's why it is called a
blueprint or template. It's all story revolves around the object.
Object
An Object can be defined as a data container with unique values for attributes and
behavior defined in its class.
In the figure 6.4.1 (b), the class car has attributes like color, maker, model, etc. The objects of car
like car1, car2 and car3 will have all the attributes of car but with its own attribute value. For
example, the first object car1 has four attributes: color is red, maker of a car is Maruti, Model is
Swift, and category of a car is Hatchback. Similarly, the second object, object 2, is car 2 with
attributes; color is white, maker of a car is Hyundai, Model is Verna, and car
category is the Sedan.
Instance
As depicted in figure 6.4.1 (b), we have taken blueprint of car as a class and created three objects
for it. The more objects of car can be created and initiated. But each individual object created,
16
presently active and initiated is known as an instance of respective object or class. Thus, an
instance is an object that is created, initiated and presently active.
Class
Attributes or variables
Methods à Variabls
Create Object
Cunstructor initiated
Figure 6.4.4. Classification of a Class and Workflow of class and its components
17
Figure 6.4.5: Components of Class and Objects
18
The figure 6.4.3. (b) shows that object creation of a class.
19
Figure 6.4.4 (a): Class Method called
20
Figure 6.4.4. (c) Demonstration of the usage of self
6.4.4.1. Can we use self as a variable name in the class? Yes. Refer figure 6.4.4.1. (a)
We have taken one more example for better understanding of self, refer figure 6.4.4.1 (b)
21
Figure 6.4.4.1. (b)
In figure 6.4.4.1 (b), there is a class named as Student and we have declared a global/class
variable named as lanugae.We have created two objects student1 and students 2.Now we call
add_lang method to add python and java laguages by student 1 and student2 respectively . If
student1 try to access class variable language than both the languages are mapped to student1.
But this shouldn’t be happening. In other words, when you append any value in the list type
variable 'language', then all the objects of the class can access the same value. Say, student1
learnt python and the value 'python' appended in the list, then student2 can also get the value
'python'. This is the main issue in class variables.
The properties which are related to object1 should not be conflict with object2. The solution of
this issue is use of 'self'
22
6.5.Constructor
The data members of an object are initialized by using constructors. In class, generally, we
have
• Attributes/ Properties
• Methods
• Objects
All classes have constructors by default: if you do not write a constructor code yourself, Python
creates one for you. However, then you are not able to set initial values for object attributes.
Figure 6.5.(a) provides the syntax of init()
In ___init__(), the first argument is always defaulted "Self." A builder may or may not have other
input parameters, i.e., optional input parameters. Init is the initialization acronym, and
___(double underscore) indicates the special init process.
In Python, when you create a new instance of a class.
For example, Car1 =CarClass() first the special method __new__() is called to create the object,
and then the special Method __init__() is called to initialize it.
Figure 6.5.(b) figure represents how the constructor of a class can create multiple instances of
the car object.
23
Figure 6.5.(b) The above figure represents how the constructor of a class can
creates multiple instances of the car object
Whenever we create an object of a class, __new__( ) method of a super class will be called and
return an instance of that class. There is no need to define (override the super class method) a
__new__() method inside the class until you want to customize the object's creation. An instance
of a class can be created inside __new__() method using super function. Figure 6.5.1. represents
concept of __new__.
Syntax -
24
Figure 6.5.1(b) Concept of __new__
In the above example, It is clearly shown that __new__() method is called before the __init__()
method for creating an object of class test.
If both, __init__() and __new__() methods exist in the class, then the __new__() method is
executed first and decide whether to use __init__ method or not.
In the above example, the class constructor, i.e., __init__( ), is called by the new method using
super function. If we omit super from __new__() method, then __init__() method will not
execute as shown in the Figure 6.5.1. (b)
25
Figure 6.5.1.(d) Visulaization
26
Figure 6.5.2. (b): Types of Constructors
6.6. Variable
Definition
Object-oriented programming allows for variables to be used at the class level or the instance
level. Variables are essentially symbols that stand in for a value you're operating in a program
demonstrated in figure 6.6.
27
Figure 6.6. Demonstration of Variables
Class variables
Class variables are declared inside the class, but these are kept outside the scope of class
methods, and these class variables are also called global variables. For example:
class A:
class_var = 10 # class variable
Instance variable
Instance variables (also called data attributes) are unique to each instance of the class, and they
are defined within a class method. For example:
class A:
class_var=10 # Class Variable
def __init__(self,int_var):
self.int_var = int_var #instance variable
The values we give to the object are passed to these variables (Instance), and that's why these
variables are called local variables.
We can observe the difference among both types of variables below the examples
mentioned. Here' radius' is the instance variable and 'pi' is the class variable.
28
Figure 6.6.1. (a) Class and instance variables demonstration
Note-In the above example, 'c' is the name of an object created by Carwheel class. Even though
the method __init__ method has two arguments(self, radius), we will pass only 'radius' while
creating the object. The value for the self is not given as arguments (Implicit calling).
29
6.6.2. How to access instance variables
6.7.Methods
A method is just a function object created by a def statement. The method works in the same
way as a simple function.
6.7.1. Types of methods in Python:
• Static Method
• Non-Static Method
31
6.7.1.2.Static Method:
Static methods are utility functions; whatever is written inside the Method, they perform
the assigned task by taking some parameters.
It does not take a positional argument (self-etc.). Static methods can be called without creating
the class's object, just by using the class name. The figure 6.7.1.2. represents calling static
method interest in line no. 11. To create a static Method in Python, we use @staticmethod
32
Types of Inheritance:
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
6.8.1.1.Single inheritance
It enables the child class to inherit from a single base class only. The figure 6.8.1.1 demonstrates
the single inheritance showing child class inherited parent class. Now, child class has two
functions display2 and dislay1.
6.8.1.3.Multilevel inheritance
If a derived class is further inherited into another derived class, then it is called multiple
inheritance. Figure 6.8.1.3. shown an example of multilevel inheritance. In this example the base
grandparent is inherited by the derived class parent. Further, parent class is inherited by child
class. Thus, class child inhibits multilevel inheritance.
33
Figure 6.8.1.2. Multiple Inheritance
34
Figure 6.8.1.4. Hierarchal Inheritance
35
Figure 6.8.2. Inherit Constructor
While creating a child object, we need to pass value because the child class inherits the parent's
constructor.
6.8.3. What will happen if our child class has its constructor?
Parent constructor will not be inherited if a child has its constructor.
The figure 6.8.3 shows that both parent and child class have their constructor. When we create
an object of the child class, then only the child class constructor is called.
6.8.4. How to inherit the parent constructor if the child has its constructor?
To inherit the parent constructor (same as true for oops), we use the super () function in Python
as shown in figure 6.8.4(a) and figure 6.8.4(b).
36
Figure 6.8.4. (a) Use of Super
37
Figure 6.8.5 (a) Method Resolution Order
The figure 6.8.5 (a) and 6.8.5 (b) shows that the method ‘rk’ is invoked from ClassChild not
ClassSuper. Therefore, the order follows is ClassChild -> ClassSuper
38
Figure 6.8.5 (c) Method Resolution Order: Multiple Inheritance
39
The figure 6.8.5 (a) shows that Python follows depth first order in multiple inheritance. It ended
at calling method from class A1. Using Method Resolution Order, the order followed is A4 -> A2
-> A3 -> A1.
6.8.2.Encapsulation
Python offers global access to all variables and processes. We'll use a few different ways to
manage the access to variables within a Python program because we don't have access
modifiers in Python.
40
While posting a post on Facebook, you will get an option to select all your friends, or anyone on
Facebook, or a set of specific people as you can opt for any one chance to share the post among
a particular group of people. You can relate this as the access modifiers in object-oriented
programming as depicted in figure 6.8.1.1.
41
mangling is the term for this process. It is also possible to reach the members of the class from
outside of it. When you declare a data member secret, you're saying that no one in the class
should be able to view it. In Python, however, the keyword 'personal' is not written directly. No
function in Python essentially limits access to any instance variable or procedure. Python
recommends prefixing the name of the variable/method with a single or double underscore to
mimic the actions of secure and private access specifiers.
A variable becomes private when it has the double underscore prefixed to it. It implies that no
one outside the class can touch it. Any attempt to do so will result in an AttributeError as shown
in figure 6.8.2.3.
Mangling
Any identifier with __Var in Python is rewritten as _Classname__Var by a Python interpreter,
and the class name remains the same. In Python, this name-changing process is known as Name
Mangling.
Using Getter and Setter methods to access private variables as depicted in figure 6.8.2.4.
42
Figure 6.8.2.4. Getter and setter
6.8.3.Abstraction
Need: To let the user know the main functionality of the module without going into details
of implementation.
For example, consider the following scenario: you've just purchased a new mobile device. Along
with the software, you get a user guide that describes how to use the program, but it provides
little detail about the device's internal workings.
Another example is when you use the TV remote and don't understand how hitting a key in the
remote switches the channel internally. You're already aware that clicking the + volume key raises
the volume.
6.8.3.1.How to implement abstraction in Python?
The abstract class is generated in Python by deriving from the metaclass ABC, which is part of
the ABC module (Abstract Base Class) as depicted in figure 6.8.3.1.
Syntax:
43
Figure 6.8.3.1. Synatx for creation of Abstract class
In the ABC module, ABC metaclass has to be imported, and the abstract class has to inherit the
ABC class to be considered an abstract class.
Points to be noted:
1. An abstract class can have both standard methods as well as abstract methods.
2. The abstract class works as a template for other classes. Using an abstract class, you can
define a generalized structure without providing complete implementation of every
Method. Methods that provide standard functionality for all derived classes are described
as concrete methods in the abstract class, whereas the methods where implementation may
vary are defined as abstract methods.
3. Abstract class can't be instantiated, so it is impossible to create objects of an abstract
class.
4. Derived classes must implement the abstract Method of a superclass. If the derived class
Python does not implement any abstract method throws an error.
5. Refer figure 6.8.3.3 (b) for abstract method in detail.
44
Output:
6.8.4.Polymorphism
One of the four basic OOPS terms is polymorphism. Polymorphism describes the tendency of a
function of the same name to perform several functions. It provides a structure that can handle
several object types like water can have many forms with different forms as shown in figure
6.8.4 (a).
45
Figure 6.8.4 (a): Multiple forms of an entity
46
The figure 6.8.4 (b) shows method age and color having two different forms in classes and Lion.
6.8.4.1.Method overloading
In Python, method overloading is something where similar method names exist in the same class
but vary in form or number of arguments transferred, which is not supported. Note that in
Python, attempting to use the same name does not cause a compile-time error; however, only
the last specified Method is remembered in such a scenario; calling some other overloaded
method causes an error as depicted in figure. 6.8.4.1 (a).
Since overloading a function of the same name is difficult in Python, method overloading is
achieved by making a single method with several parameters. You must validate the number of
arguments passed to the Method and then continue with the operation.
47
For example, if we use the same sum () method as above but transfer two or three parameters,
we can do method overloading in Python, as seen in figure 6.8.4.1 (b)
6.8.4.2.Method overriding
Method overriding allows you to modify the execution of a child class method that is already
specified in its superclass. When a child class has a superclass and a Function method of the same
name and number of arguments, the child class method overrides the parent class method. The
parent class method is implemented when the Method is called with the parent class object.
When a method is named for a child class object, the child class's method is executed.
Polymorphism is shown where the required overridden Method is called based on the object
type. Method overriding is depicted in figure 6.8.4.2 (a).
The super () function is used to gain access to a parent or sibling class's methods and properties.
Method overriding provides the ability to change the child class method's implementation, which
is already defined in its superclass. If there are a superclass and method with the same name and
the same number of arguments in a child class, then the child class method is overriding the
parent class method.
Note: When the Method is called with the parent class object, the parent class method is
executed. When Method is called with child class object, Method of the child class is
48
performed. The appropriate overridden Method is named based on the object type, which is an
example of polymorphism.
The super () function gives access to a parent or sibling class's methods and properties.
Output:
When the displayData() method is called for a Person class entity, the Person class's displayData()
method is called. When the displayData() method is called on an Employee class object, the
Employee class's displayData() method is called. As a result, the proper overridden Method is
called depending on the object type, a Polymorphism example.
49
Overriding the parent class the kid class's method
You may use the following methods to call the superclass's overridden method:
1. Making use of ClassName.method (self), refer figure 6.8.4.2. (b)
2. Make use of super (), refer figure 6.8.4.2. (c)
50
Calling superclass method using super ()
Output:
51
Figure 6.8.4.3. (a) Operator overloading
Refer the figure 6.8.4.3 (b), the '+' operator operated for Strings and Lists because it was already
overwhelmed to provide String and List features. What if you try to use a custom object with an
operator? If you're going to use the '+' operator on your custom class objects, for example.
There is a class Point with two variables, x, and y, in the example. Two Point type objects are
instantiated, and you attempt to merge their data (p1.x + p2.x) and (p1.y + p2.y) into a single
object.
Note: Python specifies methods for all operators implicitly to provide functionality for such
operators. The special method __add__, for example, provides functionality for the '+' operator
(). Internally, if the '+' operator is used, the __add__() Method is called to perform the procedure.
52
Magic or extraordinary methods in Python are internal methods that have utility for the
operators. When matching operators are used, these unique methods are automatically invoked;
if you want an operator to deal with custom objects, you must override the corresponding
particular Method that offers that operator features as shown in figure 6.8.4.3. (b).
6.8.4.4.Special/Dunder/Magic methods
The methods prefixed with two underscores and suffixed with two underscores are known as
magic methods in Python. In Python, these mystical approaches are known as Dunders (Double
UNDERscores). Magical methods for some of the most critical operators are described in the
figure 6.8.4.4 (a)
Operator Special Method Remarks
[+] __add__ It is used as an Additive operator
[-] __sub__ It is used as a Subtraction operator
[*] __mul__ It is used as a Multiplication operator
It is used as Division with the fractional
[/] __truediv__
result
[%] __mod__ It is used as the Remainder operator
Division with integer result, discarding any
[ // ] __floordiv__
fractional part
53
[ <= ] __le__ It is used as less than or equal to
__dict__
Output:
{'__module__': '__main__', 'class_var': 1, '__init__': <function MyClass.__init__ at 0x7f81774d26a8>,
'__return__': None, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute
'__weakref__' of 'MyClass' objects>, '__doc__': None}
{'i_var': 2}
54
{'i_var': 3}
The figure 6.8.4.4 (b) shows __dict__ contains all the attributes of object.
__repr__
This is another special method. Which is used to represent object as a string in python. It is called by
repr() function which is built in.
Syntax: object.__repr__(self)
A class, Person, is created with the __repr__ method. We can then call this method using the
built-in Python function repr(). It would return the object representation as string, refer figure
6.8.4.4 (c). The output will be Person (John, 20).
__str__
__str__ method in python represents Class objects as string. __str__ method is called when below
functions are called on the object and return a string.
• print()
• str()
If we have not defined the __str__ , then it will call the __repr__ method. Refer figure 6.8.4.4 (d).
55
Figure 6.8.4.4 (d) __str__
• Stack allows the addition of new elements and deletion of elements from the index called
Top of Stack.
• Stack works on the principle of Last in First Out, or First In Last Out; this is up to the
indexing which a programmer is assuming.
• The addition of the element in the stack is called PUSH(), and the deletion of an element
from the stack is known as POP(). The PUSH() and POP() operations and the Top of the
stack (alias TOS or TOP) are shown in figure below.
56
In the above-shown figure, firstly, element 10 was inserted into the empty stack. After that, 20
and 30 were added to the stack. The current position of TOP shows the Top of the stack.
57
6.9.1.3 Stack has two main operations
• PUSH () – This is an insertion method in the stack. Whenever an element is inserted into
a stack, it is through the PUSH () operation.
• POP () – This is a deletion method in the stack. Removal of an element from the stack is
through the POP () operation.
To code, the behavior of the stack in python, functions associated with the stack need to
understand first. The list of stack function is mentioned below and shown in figure 6.8.5.1(c)
58
Step 1: Create a class for stack and mention all the methods of the stack. Here,
Step 2: write code for all methods to define the working in stack.
59
After creating a class, first task is to write the code for constructor. This code decides the behavior
of the instance of the respective class. Here, in stack, the maxsize is defined as an argument to
pass while creating an abject of stack class. By default, value of TOP is –1. It can also be taken as
zero, but the zero is an index value where the element can be stored. So, the self.top is taken as
–1. maxsize is the input value at the time of object creation. As it is a fixed size stack, so the
dummy list is created in the memory to show all elements of stack are None. The same code is
shown in figure 6.8.5.1(e)
Next method in the stack class is to check whether a stack is empty or not. For this, isEmpty() method is
created. The code is shown in figure 6.8.5.1(f)
For the finite buffer or fixed size stack, the isFull() method is also required, which notifies the stack is
whether full or not. The code of the method is shown in figure 6.8.5.1(g).
60
push () and pop() are the main operations of the stack. Here, push () method is called to add an
element in the stack. While adding an element, the first thing is to check whether a stack is full
or not. This condition is also checked in the method before adding an element in stack at TOP of
stack. Figure 6.8.5.1(h) shows the code of push () method.
pop () method is called to delete or pop an element from the top of the stack. While deleting an
element, check whether a stack is empty or not. This condition is called from the isEmpty()
method and checked prior to delete an element from stack. Figure 6.8.5.1(i) shows the code of
pop () method.
peek () method shows the top most element of the stack, where the top of stack is pointing.
The code of peek () is shown in figure 6.8.5.1(j)
size () method shows the maxsize of the stack as shown in figure 6.8.5.1(k)
61
Figure 6.8.5.1(k): size () method
Step 3: create an object of stack class, as s1 = stack (5) and perform the push(), pop() and peek() operations
on stack object. Figure 6.8.5.1(l) shows the creation of s1 instance of stack class with max size 5.
Figure 6.8.5.1(m) shows the push () command to add integer value 10 in the s1 stack. Figure
6.8.5.1(n) shows the push () Stack operation as per the commands given to the python
interpreter.
62
Figure 6.8.5.1(m): push() operation to add 10 in stack
If we continuously add the elements in stack and stack reached to the maxsize, it will not push new
elements and shows an Stack full notification on console. Figure 6.8.5.1(o) shows the code and figure
6.8.5.1(p) shows the visualized output of the code.
63
Figure 6.8.5.1(o): Code to add elements in stack
Figure 6.8.5.1(q) shows the code for pop () and peek () method. Figure 6.8.5.1(r) shows the
working of pop () command and peek () command of the respective code on the stack instance
s1.
64
Figure 6.8.5.1(q): code of pop () and peek ()
Figure 6.8.5.1(r): shows the working of pop () command and peek () command
If further pop () will be called three times then the stack will reach to the empty state. The notification of
empty stack is displayed to the console as output. Figure 6.8.5.1(s) shows the code and figure 6.8.5.1(t)
shows the visualized output
65
Figure 6.8.5.1(t) visualization of pop () command till stack is empty
66
enqueue(data/object): In the very end, it adds/insert new data to the queue. The backside is
referred to as the rear end. rear () : Returns the first element from the end of the queue.
dequeue () : Removes and returns the data from the queue's front. The front is the name given
to the side. front(): Returns the first element from the start of the queue.
Step2: The method adds some information to the queue (elements). To connect data to the end
of the queue.
67
Figure 6.8.5.1(d): Adds some elements to the queue
Step3: The method deletes the information from the queue (elements).
68
Figure 6.8.5.1(e): Some supporting functions
69
Output of Insertion
Output of deletion
70
6.9.3 LinkedList and its implementation
6.9.3.1 Introduction to Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using reference as shown in the below image:
Figure 6.9.3.1:
Node - A simple type of node is one that only has a link to the next node and data. Next field is
used to store reference of next adjacent node and data field contains data.
A node consists of two attributes data and next so we can define node using class
Figure 6.9.3.2(a):
71
The next attribute is initialized to None, while creating a new node and before adding to existing linked
list.
Methods -
72
In the above figure we initialize all attributes and methods are blank. Now let's define each method in
details.
addBeg() Method
addEnd() Method
73
delBeg() Method
delEnd() Method
74
traverse() Method
A node consists of three attributes, data, next and prev. Date attributes hold info, next attributes
hold reference of next node and prev attributes hold reference of previous node.
Head attribute is used to store reference of first node and Tail attribute is used to store reference
of last node.
75
Methods -
addBeg() Method -
76
addEnd() Method -
delBeg() Method-
77
delEnd() Method() -
Traverse () Method -
78
References:
1. Head-First Python, 2nd edition by Paul Barry (O'Reilly, 2016).
2. Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to
Programming Paperback – 3 May 2019.
3. https://www.oreilly.com/library/view/learning-python-5th/9781449355722/
4. https://docs.python.org/3/distributing/index.html.
5. PCEP (Certified Entry-Level Python Programmer) -
https://pythoninstitute.org/certification/pcep-certification-entry-level/
6. PCAP (Certified Associate in Python Programming) -
https://pythoninstitute.org/certification/pcap-certification-associate/
7. https://python-course.eu/
8. Python Data Structures | Coursera University of Michigan - Python for Data Structure
https://www.coursera.org/learn/python-
9. https://www.udemy.com/course/complete-python-bootcamp
10. https://www.geeksforgeeks.org/
11. https://infytq.infosys.com/toc/lex_auth_0125409616243425281061 (Programming
Fundamentals Using Python).
12. https://www.askpython.com/python/oops
13. https://www.netjstech.com/
14. https://techvidvan.com/tutorials/category/python/
79