Lecture Notes -Ece 282 Object-Oriented-python
Lecture Notes -Ece 282 Object-Oriented-python
i
OOP in Python
Table of Contents
About the Tutorial ............................................................................................................................................ ii
Audience .......................................................................................................................................................... ii
Prerequisites .................................................................................................................................................... ii
Pycharm ......................................................................................................................................................... 10
Notepad ++ .................................................................................................................................................... 15
Lists ..................................................................................................................................... 17
OOP in Python
Accessing Items in Python List ........................................................................................................................ 18
Tuples ............................................................................................................................................................ 19
Dictionary ...................................................................................................................................................... 21
Sets ................................................................................................................................................................ 24
Encapsulation ................................................................................................................................................. 31
Inheritance ..................................................................................................................................................... 44
Overriding ...................................................................................................................................................... 48
Overview ....................................................................................................................................................... 57
OOP in Python
Why is Design Pattern Important? .................................................................................................................. 57
Strings ............................................................................................................................................................ 66
Pickle ............................................................................................................................................................. 80
Methods ........................................................................................................................................................ 81
Unpickling ...................................................................................................................................................... 82
JSON .............................................................................................................................................................. 82
YAML ............................................................................................................................................................. 85
Logging........................................................................................................................................................... 91
Benchmarking ................................................................................................................................................ 93
Indexing DataFrames...................................................................................................................................... 98
Pygame .......................................................................................................................................................... 99
This chapter talks about the features of Python programming language that makes it an
object-oriented programming language.
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.
• 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.
The table in the following image shows the major differences between POP and OOP
approach.
3
OOP in Python
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
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:
Consider a module named employee.py with a function in it called employee. The code
of the function is given below:
Now import the module and then access the function EmployeID:
import employee
employee. EmployeID()
6
OOP in Python
def EmployeID():
print (“Employee Unique Identity!”)
# just a variable
Age = “Employee age is **”
import employee
employee.EmployeID()
print(employee.Age)
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.
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.
You can instantiate an object, similar to calling a class like a function, as shown:
# 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).
Characteristics of Python
Following are important characteristics of Python Programming −
• It supports functional and structured programming methods as well as OOP.
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Applications of Python
• 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.
• 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.
• 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 Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
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.
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.
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
>>> 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.
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']
>>> 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:
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.
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 .
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.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
From the code shown above, we can understand that tuples are immutable and hence:
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:
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'
>>>
• 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:
• You cannot have duplicate keys in a dictionary. Altering the value of an existing
key will delete the old value.
18
OOP in Python
• Dictionaries have no concept of order among elements. They are simple unordered
collections.
• 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.
19