0% found this document useful (0 votes)
5 views24 pages

Lecture Notes -Ece 282 Object-Oriented-python

The document is a set of lecture notes on Object Oriented Programming (OOP) in Python, covering its principles, environment setup, data structures, and advanced features. It emphasizes the advantages of OOP, including modularity and reusability, and explains key concepts such as classes, objects, inheritance, and polymorphism. Additionally, it provides practical guidance on using Python libraries and tools for effective programming.

Uploaded by

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

Lecture Notes -Ece 282 Object-Oriented-python

The document is a set of lecture notes on Object Oriented Programming (OOP) in Python, covering its principles, environment setup, data structures, and advanced features. It emphasizes the advantages of OOP, including modularity and reusability, and explains key concepts such as classes, objects, inheritance, and polymorphism. Additionally, it provides practical guidance on using Python libraries and tools for effective programming.

Uploaded by

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

LECTURE NOTES

UNIT: OBJECT ORIENTED PROGRAMMING

UNIT CODE: ECE 282

i
OOP in Python

Table of Contents
About the Tutorial ............................................................................................................................................ ii

Audience .......................................................................................................................................................... ii

Prerequisites .................................................................................................................................................... ii

OOP IN PYTHON – INTRODUCTION ............................................................................................. 1

Language Programming Classification Scheme ................................................................................................. 1

What is Object Oriented Programming? ........................................................................................................... 2

Why to Choose Object-oriented programming?................................................................................................ 2

Procedural vs. Object Oriented Programming ................................................................................................... 2

Principles of Object Oriented Programming ...................................................................................................... 3

Object-Oriented Python ................................................................................................................................... 5

Modules vs. Classes and Objects ...................................................................................................................... 5

OOP IN PYTHON – ENVIRONMENT SETUP ................................................................................... 8

Prerequisites and Toolkits ................................................................................................................................ 8

Installing Python .............................................................................................................................................. 8

Choosing an IDE ............................................................................................................................................. 10

Pycharm ......................................................................................................................................................... 10

Komodo IDE ................................................................................................................................................... 11

Eric Python IDE ............................................................................................................................................... 12

Choosing a Text Editor .................................................................................................................................... 13

Atom Text Editor ............................................................................................................................................ 13

Screenshot of Atom text................................................................................................................................. 14

Sublime Text Editor ........................................................................................................................................ 14

Notepad ++ .................................................................................................................................................... 15

OOP IN PYTHON – DATA STRUCTURES ...................................................................................... 17

Lists ..................................................................................................................................... 17
OOP in Python
Accessing Items in Python List ........................................................................................................................ 18

Empty Objects ................................................................................................................................................ 18

Tuples ............................................................................................................................................................ 19

Dictionary ...................................................................................................................................................... 21

Sets ................................................................................................................................................................ 24

OOP IN PYTHON – BUILDING BLOCKS ........................................................................................ 28

Class Bundles : Behavior and State ................................................................................................................. 28

Creation and Instantiation .............................................................................................................................. 29

Instance Methods .......................................................................................................................................... 30

Encapsulation ................................................................................................................................................. 31

Init Constructor .............................................................................................................................................. 33

Class Attributes .............................................................................................................................................. 34

Working with Class and Instance Data ............................................................................................................ 35

OOP IN PYTHON – OBJECT ORIENTED SHORTCUT ..................................................................... 37

Python Built-in Functions ............................................................................................................................... 37

Default Arguments ......................................................................................................................................... 42

OOP IN PYTHON – INHERITANCE AND POLYMORPHISM ........................................................... 44

Inheritance ..................................................................................................................................................... 44

Inheriting Attributes ....................................................................................................................................... 44

Inheritance Examples ..................................................................................................................................... 45

Polymorphism (“MANY SHAPES”) ........................................................................................................................ 47

Overriding ...................................................................................................................................................... 48

Inheriting the Constructor .............................................................................................................................. 49

Multiple Inheritance and the Lookup Tree ...................................................................................................... 50

Decorators, Static and Class Methods............................................................................................................. 54

OOP IN PYTHON –PYTHON DESIGN PATTERN ............................................................................ 57

Overview ....................................................................................................................................................... 57
OOP in Python
Why is Design Pattern Important? .................................................................................................................. 57

Classification of Design Patterns..................................................................................................................... 57

Commonly used Design Patterns .................................................................................................................... 58

OOP IN PYTHON – ADVANCED FEATURES ................................................................................. 60

Core Syntax in our Class design ...................................................................................................................... 60

Inheriting From built-in types ......................................................................................................................... 61

Naming Conventions ...................................................................................................................................... 63

OOP IN PYTHON – FILES AND STRINGS ...................................................................................... 65

Strings ............................................................................................................................................................ 66

File I/O ........................................................................................................................................................... 71

OOP IN PYTHON – EXCEPTION AND EXCEPTION CLASSES .......................................................... 72

Identifying Exception (Errors) ......................................................................................................................... 72

Catching/Trapping Exception .......................................................................................................................... 73

Raising Exceptions .......................................................................................................................................... 75

Creating Custom exception class .................................................................................................................... 76

OOP IN PYTHON – OBJECT SERIALIZATION ................................................................................ 80

Pickle ............................................................................................................................................................. 80

Methods ........................................................................................................................................................ 81

Unpickling ...................................................................................................................................................... 82

JSON .............................................................................................................................................................. 82

YAML ............................................................................................................................................................. 85

Installing YAML .............................................................................................................................................. 85

PDB – The Python Debugger ........................................................................................................................... 89

Logging........................................................................................................................................................... 91

Benchmarking ................................................................................................................................................ 93

12. OOP IN PYTHON – PYTHON LIBRARIES................................................................................. 96

Requests: Python Requests Module ............................................................................................................... 96


OOP in Python
Making a GET Request.................................................................................................................................... 96

Making POST Requests ................................................................................................................................... 97

Pandas: Python Library Pandas....................................................................................................................... 97

Indexing DataFrames...................................................................................................................................... 98

Pygame .......................................................................................................................................................... 99

Beautiful Soup: Web Scraping with Beautiful Soup ....................................................................................... 102


OOP in Python
1. OOP in Python – Introduction

Programming languages are emerging constantly, and so are different methodologies.


Object-oriented programming is one such methodology that has become quite popular
over past few years.

This chapter talks about the features of Python programming language that makes it an
object-oriented programming language.

Language Programming Classification Scheme


Python can be characterized under object-oriented programming methodologies. The
following image shows the characteristics of various programming languages. Observe the
features of Python that makes it object-oriented.

1
OOP in Python
What is Object Oriented Programming?
Object Oriented programming (OOP), is a way of programming that focuses on
using objects and classes to design and build applications..
It means directed towards objects. In other words, it means functionally directed
towards modelling objects. This is one of the many techniques used for modelling complex
systems by describing a collection of interacting objects via their data and behavior.
Definition: Object-Oriented Programming (OOP) is a programming paradigm based on
the concept of "objects," which can contain data (attributes) and code (methods).
Purpose: Promotes modularity, reusability, and scalability in software development.
Object is a data structure that encapsulates data (attributes or properties) and the
behaviors (methods or functions) that operate on that data. Objects are a core concept
in object-oriented programming (OOP) and are instances of classes, which define the
blueprint or template for the object.
Class: A blueprint or template for creating objects. It defines the structure and behavior
that the objects of the class will have.

Object: An instance of a class. Has a unique identity and its own state (values for the
attributes).

Object Oriented Analysis(OOA) is the process of examining a problem, system or task and
identifying the objects and interactions between them.

2
OOP in Python
Why to Choose Object Oriented Programming?
Python was designed with an object-oriented approach. OOP offers the following
advantages:

• Provides a clear program structure, which makes it easy to map real world problems
and their solutions.

• Facilitates easy maintenance and modification of existing code.

• Enhances program modularity because each object exists independently and new
features can be added easily without disturbing the existing ones.

• Presents a good framework for code libraries where supplied components can be
easily adapted and modified by the programmer.

• Imparts code reusability

Procedural vs. Object Oriented Programming


Procedural based programming is derived from structural programming based on the
concepts of functions/procedure/routines. It is easy to access and change the data in
procedural oriented programming. On the other hand, Object Oriented Programming
(OOP) allows decomposition of a problem into a number of units called objects and then
build the data and functions around these objects. It emphasis more on the data than
procedure or functions. Also in OOP, data is hidden and cannot be accessed by external
procedure.

The table in the following image shows the major differences between POP and OOP
approach.

3
OOP in Python

Principles/Principles of Object Oriented Programming


Object Oriented Programming (OOP) is based on the concept of objects rather than
actions, and data rather than logic. In order for a programming language to be object-
oriented, it should have a mechanism to enable working with classes and objects as well
as the implementation and usage of the fundamental object-oriented principles and
concepts namely inheritance, abstraction, encapsulation and polymorphism.

Let us understand each of the pillars of object-oriented programming in brief:

Encapsulation
This property hides unnecessary details and makes it easier to manage the program
structure. Each object’s implementation and state are hidden behind well-defined
boundaries and that provides a clean and simple interface for working with them. One way
to accomplish this is by making the data private.

Inheritance
Inheritance, also called generalization, allows us to capture a hierarchal relationship
between classes and objects. For instance, a ‘fruit’ is a generalization of ‘orange’.
Inheritance is very useful from a code reuse perspective.

Abstraction
This property allows us to hide the details and expose only the essential features of a
concept or object. For example, a person driving a scooter knows that on pressing a horn,
sound is emitted, but he has no idea about how the sound is actually generated on pressing
the horn.

Polymorphism
Poly-morphism means many forms. That is, a thing or action is present in different forms
or ways. One good example of polymorphism is constructor overloading in classes.

4
OOP in Python
Object-Oriented Python
The heart of Python programming is object and OOP, however you need not restrict
yourself to use the OOP by organizing your code into classes. OOP adds to the whole
design philosophy of Python and encourages a clean and pragmatic way to programming.
OOP also enables in writing bigger and complex programs.

5
OOP in Python

Modules vs. Classes and Objects

Modules are like “Dictionaries”


When working on Modules, note the following points:

• A Python module is a package to encapsulate reusable code.


• Modules reside in a folder with a init .py file on it.
• Modules contain functions and classes.
• Modules are imported using the import keyword.

Recall that a dictionary is a key-value pair. That means if you have a dictionary with a
key EmployeID and you want to retrieve it, then you will have to use the following lines
of code:

employee = {“EmployeID”: “Employee Unique Identity!”}


print (employee [‘EmployeID])

You will have to work on modules with the following process:

• A module is a Python file with some functions or variables in it.


• Import the file you need.
• Now, you can access the functions or variables in that module with the ‘.’ (dot)
Operator.

Consider a module named employee.py with a function in it called employee. The code
of the function is given below:

# this goes in employee.py


def EmployeID():
print (“Employee Unique Identity!”)

Now import the module and then access the function EmployeID:

import employee
employee. EmployeID()

6
OOP in Python

You can insert a variable in it named Age, as shown:

def EmployeID():
print (“Employee Unique Identity!”)
# just a variable
Age = “Employee age is **”

Now, access that variable in the following way:

import employee
employee.EmployeID()
print(employee.Age)

Now, let’s compare this to dictionary:

Employee[‘EmployeID’] # get EmployeID from employee


Employee.employeID() # get employeID from the module
Employee.Age # get access to variable

Notice that there is common pattern in Python:

• Take a key = value style container


• Get something out of it by the key’s name

When comparing module with a dictionary, both are similar, except with the following:

• In the case of the dictionary, the key is a string and the syntax is [key].
• In the case of the module, the key is an identifier, and the syntax is .key.

Classes are like Modules


Module is a specialized dictionary that can store Python code so you can get to it with the
‘.’ Operator. A class is a way to take a grouping of functions and data and place them
inside a container so you can access them with the ‘.‘operator.

If you have to create a class similar to the employee module, you can do it using the
following code:

class employee(object):
def init (self):
self. Age = “Employee Age is ##”
def EmployeID(self):
print (“This is just employee unique identity”)

7
OOP in Python

Note: Classes are preferred over modules because you can reuse them as they are and
without much interference. While with modules, you have only one with the entire
program.

Objects are like Mini-imports


A class is like a mini-module and you can import in a similar way as you do for classes,
using the concept called instantiate. Note that when you instantiate a class, you get an
object.

You can instantiate an object, similar to calling a class like a function, as shown:

this_obj = employee() # Instantiatethis_obj.EmployeID() #


get EmployeId from the class
print(this_obj.Age) # get variable Age

You can do this in any of the following three ways:

# dictionary style
Employee[‘EmployeID’]
# module style
Employee.EmployeID()
Print(employee.Age)
# Class style
this_obj = employee()
this_obj.employeID()
Print(this_obj.Age)

8
OOP in Python

OOP in Python
2. OOP – introduction to Python
Python is a very popular general-purpose interpreted, interactive, object-oriented,
and high-level programming language. Python is dynamically-typed and garbage-
collected programming language.

It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source
code is also available under the GNU General Public License (GPL).

Python supports multiple programming paradigms, including Procedural, Object


Oriented and Functional programming language. Python design philosophy
emphasizes code readability with the use of significant indentation.
Python "Hello, World!"

Characteristics of Python
Following are important characteristics of Python Programming −
• It supports functional and structured programming methods as well as OOP.

• It can be used as a scripting language or can be compiled to byte-code for


building large applications.

• It provides very high-level dynamic data types and supports dynamic type
checking.

• It supports automatic garbage collection.

• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Applications of Python

Python is a general purpose programming language known for its readability. It is


widely applied in various fields.

• In Data Science, Python libraries like Numpy, Pandas, and Matplotlib are used for
data analysis and visualization.

• Python frameworks like Django, and Pyramid, make the development and
deployment of Web Applications easy.

• This programming language also extends its applications to computer vision and
image processing.

9
OOP in Python
• It is also favored in many tasks like Automation, Job Scheduling, GUI
development, etc.

Features of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most
widely used languages on the web
• Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.

Its features such as simple syntax, usage of indentation to avoid clutter of curly
brackets and dynamic typing that doesn't necessitate prior declaration of
variable help a beginner to learn Python quickly and easily.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.

• Easy-to-maintain − Python's source code is fairly easy-to-maintain.

• A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.

• Interactive Mode − Python has support for an interactive mode that allows
interactive testing and debugging of snippets of code.

• Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.

• Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.

• Databases − Python provides interfaces to all major commercial databases.

• GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries, and Windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.

• Scalable − Python provides a better structure and support for large programs
than shell scripting.

Python is a high-level, interpreted, interactive and object-oriented scripting language.


Python is designed to be highly readable. It uses English keywords frequently where
as other languages use punctuation, and it has fewer syntactical constructions than
other languages.
• Python is Interpreted − Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is similar to
PERL and PHP.

• Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.

• Python is Object-Oriented − Python supports Object-Oriented style or


technique of programming that encapsulates code within objects.

10
OOP in Python
• Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

Frequently Asked Questions - About Python History


• Who created Python?

o Python created by Guido Van Rossum, a Dutch Programmer.

• Why Python is called Python?

o Python does not have any relation to Snake. The name of the Python
programming language was inspired by a British Comedy Group Monty
Python.

• When was Python's first version released?

o Python's first version was released in February 1991.

• What was the first version of Python?

o Python's first version was Python 0.9.0

• When was Python 3.0 version released?

o Python 3.0 version was released in December 2008.

Python is a feature-rich, high-level, interpreted, interactive, and object-oriented


scripting language. Python is a versatile and very popular programming language due
to its features such as readability, simplicity, extensive libraries, and many more

Choosing an IDE
An Integrated Development Environment is a text editor geared towards software
development. You will have to install an IDE to control the flow of your programming and to
group projects together when working on Python. Here are some of IDEs avaialable online. You
can choose one at your convenience.
• Pycharm IDE
• Komodo IDE
• Eric Python IDE

Note: Eclipse IDE is mostly used in Java, however it has a Python plugin.
Choosing a Text Editor
You may not always need an IDE. For tasks such as learning to code with Python or Arduino,
or when working on a quick script in shell script to help you automate some tasks a simple
and light weight code-centric text editor will do. Also many text
editors offer features such as syntax highlighting and in-program script execution, similar to
IDEs. Some of the text editors are given here:

• Atom
• Sublime Text
• Notepad++

11
OOP in Python
3. OOP in Python – Data Structures

Recap Data types


The data stored in memory can be of many types, including:
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20 >>>
print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)

>>> a=11
>>> print(type(a))

DATA STRUCTURES
Python data structures are very intuitive from a syntax point of view and they offer a large
choice of operations. You need to choose Python data structure depending on what the
data involves, if it needs to be modified, or if it is a fixed data and what access type is
required, such as at the beginning/end/random etc.

Lists
A List represents the most versatile type of data structure in Python. A list is a container
which holds comma-separated values (items or elements) between square brackets. Lists
are helpful when we want to work with multiple related values. As lists keep data together,
we can perform the same methods and operations on multiple values at once. Lists indices
start from zero and unlike strings, lists are mutable.

Data Structure - List

12
>>>
>>> # Any Empty List
>>> empty_list = []
>>>
>>> # A list of String
>>> str_list = ['Life', 'Is', 'Beautiful']
>>> # A list of Integers
>>> int_list = [1, 4, 5, 9, 18]
>>>
>>> #Mixed items list
>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>> # To print the list
>>>
>>> print(empty_list)
[]
>>> print(str_list)
['Life', 'Is', 'Beautiful']
>>> print(type(str_list))
<class 'list'>
>>> print(int_list)
[1, 4, 5, 9, 18]

13
OOP in Python

>>> print(mixed_list)
['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']

Accessing Items in Python List


Each item of a list is assigned a number – that is the index or position of that number.
Indexing always start from zero, the second index is one and so forth. To access items in
a list, we can use these index numbers within a square bracket. Observe the following
code for example:

>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>>
>>> # To access the First Item of the list
>>> mixed_list[0]
'This'
>>> # To access the 4th item
>>> mixed_list[3]
18
>>> # To access the last item of the list
>>> mixed_list[-1]
'list'

Empty Objects
Empty Objects are the simplest and most basic Python built-in types. We have used them
multiple times without noticing and have extended it to every class we have created. The
main purpose to write an empty class is to block something for time being and later extend
and add a behavior to it.

To add a behavior to a class means to replace a data structure with an object and change
all references to it. So it is important to check the data, whether it is an object in disguise,
before you create anything. Observe the following code for better understanding:

>>> #Empty objects


>>>
>>> obj = object()
>>> obj.x = 9
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
obj.x = 9
AttributeError: 'object' object has no attribute 'x'

14
OOP in Python

So from above, we can see it’s not possible to set any attributes on an object that was
instantiated directly. When Python allows an object to have arbitrary attributes, it takes a
certain amount of system memory to keep track of what attributes each object has, for
storing both the attribute name and its value. Even if no attributes are stored, a certain
amount of memory is allocated for potential new attributes.

So Python disables arbitrary properties on object and several other built-ins, by default.

>>> # Empty Objects


>>>
>>> class EmpObject:
pass
>>> obj = EmpObject()
>>> obj.x = 'Hello, World!'
>>> obj.x
'Hello, World!'

Hence, if we want to group properties together, we could store them in an empty object
as shown in the code above. However, this method is not always suggested. Remember
that classes and objects should only be used when you want to specify both data and
behaviors.

Tuples
Tuples are similar to lists and can store elements. However, they are immutable, so we
cannot add, remove or replace objects. The primary benefits tuple provides because of its
immutability is that we can use them as keys in dictionaries, or in other locations where
an object requires a hash value.

Tuples are used to store data, and not behavior. In case you require behavior to
manipulate a tuple, you need to pass the tuple into a function(or method on another
object) that performs the action.

As tuple can act as a dictionary key, the stored values are different from each other. We
can create a tuple by separating the values with a comma. Tuples are wrapped in
parentheses but not mandatory. The following code shows two identical assignments .

>>> stock1 = 'MSFT', 95.00, 97.45, 92.45


>>> stock2 = ('MSFT', 95.00, 97.45, 92.45)
>>> type (stock1)
<class 'tuple'>
>>> type(stock2)
<class 'tuple'>
>>> stock1 == stock2
True
>>>

15
OOP in Python

Defining a Tuple
Tuples are very similar to list except that the whole set of elements are enclosed in
parentheses instead of square brackets.

Just like when you slice a list, you get a new list and when you slice a tuple, you get a new
tuple.

>>> tupl = ('Tuple','is', 'an','IMMUTABLE', 'list')


>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl[0]
'Tuple'
>>> tupl[-1]
'list'
>>> tupl[1:3]
('is', 'an')

Python Tuple Methods


The following code shows the methods in Python tuples:

>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl.append('new')
Traceback (most recent call last):
File "<pyshell#148>", line 1, in <module>
tupl.append('new')
AttributeError: 'tuple' object has no attribute 'append'
>>> tupl.remove('is')
Traceback (most recent call last):
File "<pyshell#149>", line 1, in <module>
tupl.remove('is')
AttributeError: 'tuple' object has no attribute 'remove'
>>> tupl.index('list')
4
>>> tupl.index('new')
Traceback (most recent call last):
File "<pyshell#151>", line 1, in <module>
tupl.index('new')

16
OOP in Python

ValueError: tuple.index(x): x not in tuple


>>> "is" in tupl
True
>>> tupl.count('is')
1

From the code shown above, we can understand that tuples are immutable and hence:

• You cannot add elements to a tuple.


• You cannot append or extend a method.
• You cannot remove elements from a tuple.
• Tuples have no remove or pop method.
• Count and index are the methods available in a tuple.

Dictionary
Dictionary is one of the Python’s built-in data types and it defines one-to-one relationships
between keys and values.

Defining Dictionaries
Observe the following code to understand about defining a dictionary:

>>> # empty dictionary


>>> my_dict = {}
>>>
>>> # dictionary with integer keys
>>> my_dict = { 1:'msft', 2: 'IT'}
>>>
>>> # dictionary with mixed keys
>>> my_dict = {'name': 'Aarav', 1: [ 2, 4, 10]}
>>>
>>> # using built-in function dict()
>>> my_dict = dict({1:'msft', 2:'IT'})
>>>
>>> # From sequence having each item as a pair
>>> my_dict = dict([(1,'msft'), (2,'IT')])
>>>
>>> # Accessing elements of a dictionary
>>> my_dict[1]

17
OOP in Python

'msft'
>>> my_dict[2]
'IT'
>>> my_dict['IT']
Traceback (most recent call last):
File "<pyshell#177>", line 1, in <module>
my_dict['IT']
KeyError: 'IT'
>>>

From the above code we can observe that:

• First we create a dictionary with two elements and assign it to the variable
my_dict. Each element is a key-value pair, and the whole set of elements is
enclosed in curly braces.

• The number 1 is the key and msft is its value. Similarly, 2 is the key and IT is its
value.

• You can get values by key, but not vice-versa. Thus when we try my_dict[‘IT’] ,
it raises an exception, because IT is not a key.

Modifying Dictionaries
Observe the following code to understand about modifying a dictionary:

>>> # Modifying a Dictionary


>>>
>>> my_dict
{1: 'msft', 2: 'IT'}
>>> my_dict[2] = 'Software'
>>> my_dict
{1: 'msft', 2: 'Software'}
>>>
>>> my_dict[3] = 'Microsoft Technologies'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}

From the above code we can observe that:

• You cannot have duplicate keys in a dictionary. Altering the value of an existing
key will delete the old value.

• You can add new key-value pairs at any time.

18
OOP in Python

• Dictionaries have no concept of order among elements. They are simple unordered
collections.

Mixing Data types in a Dictionary


Observe the following code to understand about mixing data types in a dictionary:

>>> # Mixing Data Types in a Dictionary


>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}
>>> my_dict[4] = 'Operating System'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>> my_dict['Bill Gates'] = 'Owner'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}

From the above code we can observe that:

• Not just strings but dictionary value can be of any data type including strings,
integers, including the dictionary itself.

• Unlike dictionary values, dictionary keys are more restricted, but can be of any type
like strings, integers or any other.

Deleting Items from Dictionaries


Observe the following code to understand about deleting items from a dictionary:

>>> # Deleting Items from a Dictionary


>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}
>>>
>>> del my_dict['Bill Gates']
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>>
>>> my_dict.clear()
>>> my_dict
{}

19

You might also like