Python - 1 Year - Unit-5
Python - 1 Year - Unit-5
by
C. RAJEEV
C. RAJEEV
Assistant Professor,
Assist. Prof.
Department of CSE,
Dept. of. CSE,
MRECW MRECW.
UNIT V
Python Packages, Python Libraries, Python Modules, Collection Module, Math Module, OS
Module, Random Module, Statistics Module, Sys Module, Date & Time Module, Loading the
Module in our Python Code, import Statement, from-import Statement, Renaming a Module,
Inheritance, Polymorphism, Data Abstraction, Encapsulation, Python Class and Objects, Creating
Classes in Python, Creating an Instance of the Class, Python Constructor, Creating the,
Class Functions, In-built Class Attributes, Python Inheritance, Python Multi-Level Inheritance,
Graphical User Interface (GUI) Programming, Python Tkinter, Tkinter Geometry, pack()
1. Python Packages:
Modular programming :
Modular programming refers to the process of breaking a large, unwieldy programming task
into separate, smaller, more manageable subtasks or modules. Individual modules can then be
cobbled together like building blocks to create a larger application.
As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.
Similarly, as a directory can contain subdirectories and files, a Python package can have
sub-packages and modules.
Using a Package
Once the package is installed, it is ready to use. Import the "camelcase" package into your project.
Example
Import and use "camelcase":
Program: capitalizes the first letter of each word in text
import camelcase Output: Hello
c = camelcase.CamelCase() World
The PIP Package Manager will ask you to confirm that you want to remove the camelcase package:
Uninstalling camelcase-02.1:
Would remove:
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase-0.2
py3.6.egg-info
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase\*
Proceed (y/n)?
Press y and the package will be removed.
List Packages
Use the list command to list all the packages installed on your system:
Example
List installed packages:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip list
Result:
Package Version
--------------------------------
camelcase 0.2
mysql-connector 2.1.6
pip 18.1
pymongo 3.6.1
setuptools 39.0.1
NOTE
In google coalb, !pip install Django
Features of PIP :
Pip is already installed for versions above Python 2.7.9 or Python 3 and above .
PIP can be installed through the system package manager or by invoking cURL,
a client-side data transfer tool.
Users not only install a package but also uninstall it very easily .
PIP also manages the list of packages along with its version numbers.
2. PYTHON MODULES
What are modules in Python?
If we need to reuse the code then we can define functions, but if we need to reuse
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables.
for e.g.: example.py, is called a module and its module name would be example.
Modules provide reusability of code. Modules provides us the flexibility to organize the
code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Modules are three types:
1. Standard modules
2. User-defined modules
3. Third party modules
1.Standard modules:
These modules are already defined and kept in python software .so, when we install
python then automatically these standards modules will install in our machine.
Ex: math, calender, os, sys,..etc
2. User-defined modules
These modules are defined by user as per their requirement .so, here .py file contains
methods, variables, and classes.
3. Third party modules:
These modules are already defined by some other people and kept in internet . So
that, we can download and install in our machines by using PIP(pyhton package
installing)
PIP is a package management system used to install and manage software packages
written in python like.. Django, Flask, Pyramid ,SQLAlchemy, numpy, scipy,
3. Loading the Module in our Python Code
We can import module in three ways:
1. import <module_name>
2. from <module_name> import <method_name>
3. from <module_name> import *
1. import <module_name>:
We can import all methods which is presented in that specified modules
Ex: import math
print(math.pi)
We can import all methods which are available in math module
2. from <module_name> import <method_name>:
This import statement will import a particular method from the module which is
specified in import statement.
Ex: from math import pi
print(pi)
We cannot use other methods which are available in that module.
But, we need to avoid this type of modules as they may cause name clashes in the
current python file
3. from <module_name> import * :
This import statement will import all methods from the specified module and also we
can import all names(definitions) from a module
all the functions and constants can be imported using *.
Ex: from math import *
print(pi)
print(factorial(6))
importing everything with the asterisk (*) symbol is not a good programming
4. Renaming a Module
We can import a module by renaming it as follows.
>>> import math
>>> math.pi
3.141592653589793
['','C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\idlelib', 'C:\\Users\\
ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\ajee\\AppData\\
Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\
Python\\Python37-32\\lib', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\
ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32’,
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site- packages\\
win32\\lib',
‘C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\
Pythonwin‘]
In ubuntu python, module search path is like--
>>> import sys
>>> print '\n'.join(sys.path)
/usr/local/lib/python27.zip
/usr/local/lib/python2.7
/usr/local/lib/python2.7/plat-linux2
/usr/local/lib/python2.7/lib-tk
/usr/local/lib/python2.7/lib-old
/usr/local/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/site-packages
It's possible to find out where a module is located after it has been imported, Using __file__
>>> import random # built_in module
>>> random.__file__
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\random.py‘
>>> import fact # user defined module
enter a number:5
Factorial of 5 is: 120
>>> fact.__file__
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\fact.py‘
But, __file__ attribute is not present for C modules that are statically linked into the interpreter.
Like math, sys, time, itertools modules
Output
>>> import math
Traceback (most recent call last):
>>> math.__file__
File "<pyshell#28>", line 1, in <module>
math.file
AttributeError: module 'math' has no attribute 'file'
To know the C modules that are statically linked into the interpreter.
Execute the below command
>>> import sys
>>> print(sys.builtin_module_names)
Python provides a more efficient way of doing this. We can use the reload() function inside
the imp module to reload a module. We can do it in the following ways:
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>
dir() built-in function
We can use the dir() function to find out names that are defined inside a module.
>>>import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf',
'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf',
'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
Here, we can see a sorted list of names . All other names that begin with an underscore are
default Python attributes associated with the module (not user-defined).
For example, the __name__ attribute contains the name of the module.
import math
>>> math.__name__
'math’
All the names defined in our current namespace can be found out using the dir() function
without any arguments.
In the following code, even though the 4th index was not initialized, the compiler still
returns a value, 0, when we try to access it.
In dicitionary, In collection,
dict={'one': 1, 'two': 2, 'three': 3} from collections import defaultdict
#print(dict) nums = defaultdict(int)
print(dict['one']) nums['one'] = 1
print(dict['four']) nums['two'] = 2
Output nums['three'] = 3
1 print(nums['three'])
KeyError: 'four' print(nums['four'])
Output
3
2. Counter
Counter is a built-in data structure which is used to count the occurrence of each value
present in an array or list.
Ex
from collections import Counter
list = [1,2,3,4,1,2,6,7,3,8,1,2,2]
answer = Counter(list)
print(answer)
print(answer[2])
output
Counter({2: 4, 1: 3, 3: 2, 4: 1, 6: 1, 7: 1, 8: 1})
4
3. Deque
Deque is an optimal version of list used for inserting and removing items. It can add/remove
items from either start or the end of the list. In collections,
Ex In list,
from collections import deque
list = ["a","b","c"]
list = ["a","b","c"]
list.append("z")
deq = deque(list)
print(list)
print(deq)
list.appendleft("z")
deq.append("z")
print(list)
print(deq)
list.pop()
deq.appendleft("g")
print(list)
print(deq)
list.popleft()
deq.pop()
print(list) deque(['a', 'b', 'c'])
print(deq)
['a', 'b', 'c', 'z']
deq.popleft() deque(['a', 'b', 'c', 'z'])
AttributeError: 'list' object has no
attribute‘appendleft' print(deq) deque(['g', 'a', 'b', 'c', 'z'])
['a', 'b', 'c'] deque(['g', 'a', 'b', 'c'])
AttributeError: 'list' object has no attribute 'popleft'
4. namedtuple( )
It returns a tuple with a named entry, which means there will be a name assigned to
each value in the tuple.
It overcomes the problem of accessing the elements using the index values.
With namedtuple( ) it becomes easier to access these values, since you do not have to
remember the index values to get specific elements.
from collections import namedtuple
Student = namedtuple('Student', 'fname, lname, age')
s1 = Student('Peter', 'James', '13')
print(s1.fname)
print(s1)
output
Peter
Student(fname='Peter', lname='James', age='13')
5. ChainMap
ChainMap combines a lot of dictionaries together and returns a list of dictionaries.
ChainMaps basically encapsulates a lot of dictionaries into one single unit with no
restriction on the number of dictionaries.
Ex
import collections
dictionary1 = { 'a' : 1, 'b' : 2 }
dictionary2 = { 'c' : 3, 'b' : 4 }
chain_Map = collections.ChainMap(dictionary1, dictionary2)
print(chain_Map.maps)
Output
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}]
6. OrderedDict
OrderedDict is a dictionary that ensures its order is maintained.
For example, if the keys are inserted in a specific order, then the order is maintained. Even
if you change the value of the key later, the position will remain the same.
Ex
In dicitonary, (order is not maintained)
statesAndCapitals = { 'Gujarat' : 'Gandhinagar', 'Maharashtra' : 'Mumbai', 'Rajasthan' :
'Jaipur', Bihar' : 'Patna’}
print('List Of given states:\n') Output:
# Iterating over keys List Of given states:
for state in statesAndCapitals: Rajasthan
print(state) Bihar
Maharashtra
Gujarat
In order to maintain the order of keys and values in a dictionary, use OrderedDict().
Program:
from collections import OrderedDict
statesAndCapitals = OrderedDict([ Output:
('Gujarat', 'Gandhinagar'), List Of given states:
('Maharashtra', 'Mumbai'), Gujarat
('Rajasthan', 'Jaipur'), Maharashtra
('Bihar', 'Patna') Rajasthan
]) Bihar
print('List Of given states:\n')
# Iterating over keys
for state in statesAndCapitals:
print(state)
8. Math module:
# importing built-in module math >>> math.ceil(10.9)
import math
11
# using square root(sqrt) function contained
# in math module >>> math.floor(10.9)
print math.sqrt(25)
10
# using pi function contained in math module >>> math.fabs(10)
print math.pi
10.0
# 2 radians = 114.59 degreees >>> math.fabs(-10)
print math.degrees(2)
10.0
# 60 degrees = 1.04 radians >>> math.fmod(10,2)
print math.radians(60)
0.0
# Sine of 2 radians >>> math.fsum([1,2,4])
print math.sin(2)
7.0
# Cosine of 0.5 radians >>> math.pow(2,3)
print math.cos(0.5)
8.0
>>> math.factorial(4)
# Tangent of 0.23 radians
24
print math.tan(0.23)
9. OS Module:
OS module provides functions for interacting with the operating system.
OS, comes under Python’s standard utility modules. This module provides a portable
way of using operating system dependent functionality.
1.os.name:
This function gives the name of the operating system dependent module(real module )
imported.
>>> import os
>>> os.name
'nt'
2. os.getcwd()
A directory or folder is a collection of files and sub directories.
We can get the present working directory using the getcwd() method.
This method returns the current working directory in the form of a string. We can also
use the getcwdb() method to get it as bytes object.
Ex:
>>> import os
>>> os.getcwd()
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32‘
>>> os.getcwdb()
b'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-
32‘
The extra backslash implies escape sequence.
>>> print(os.getcwd())
C:\Users\ajee\AppData\Local\Programs\Python\Python37-32
3. os.chdir()
We can change the current working directory using the chdir() method.
Ex:
>>> os.chdir('C:\\Python3')
>>> os.getcwd()
'C:\\Python3'
>>> print(os.getcwd())
C:\Python3
4. os.listdir()
All files and sub directories inside a directory can be known using the listdir() method.
This method takes in a path and returns a list of sub directories and files in that path.
>>> import os
>>> print(os.getcwd())
C:\Users\ajee\AppData\Local\Programs\Python\Python37-32
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib', 'libs',
If the full path is not specified, the new directory is created in the current working
directory.
>>> os.mkdir('test')
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib',
The first argument is the old name and the new name must be supplies as the second
argument.
>>> os.rename('test','new_test')
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib',
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs‘, 'empty file‘, ‘non-
empty file’]
>>> os.remove('demo.txt')
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo1', 'DLLs‘, 'empty file‘, ‘non-empty file’]
>>>os.rmdir('empty file')
>>>os.rmdir('non-empty file')
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
os.rmdir('non-empty file')
OSError: [WinError 145] The directory is not empty: 'non-empty file‘
Ex
import sys
sys.stdout.write(‘hi I am standard files')
Output:
hi I am standard files
4. sys.stderr
This function of sys module is used to error message.
This function is standard file in python
Syntax:
sys.stderr.write()
Ex
import sys
sys.stderr.write(‘name a is not defined’)
Output:
name a is not defined
5. sys.version
To know the version of python
Ex
import sys
sys.version
output
3.7.10 (default, May 3 2021, 02:48:31) [GCC 7.5.0]
6. sys.exit
This method makes the Python interpretor exits the current flow of execution abruptly
Ex
import sys
print("python programming")
sys.exit(1)
print("datascience")
Output
python programming
7. sys.copyright
This function displays the copyright information on currently installed Python version.
Ex
import sys
sys.copyright
Output
Copyright (c) 2001-2021 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
8. sys.maxsize
This function returns the largest integer of a variable.
Ex
import sys
sys.maxsize
Output
9223372036854775807
8. sys.argv or Command line arguments :
Command line arguments in python:
Almost all programming language provide support for command line arguments. Then we
also have command line options to set some specific options for the program in python.
The command line arguments are those arguments must be given whenever we want to
give the input before the start of the script.
These arguments are given on the command line along with the program name in a text-
based environment like a unix- or dos-shell.
However, in an IDE or GUI environment, this would not be the case. Most IDES provide
a separate window with which to enter your "command-line arguments." These will be
passed into the program as if you started your application from the command line.
There are many options to read python command line arguments. One of most common
1. Python sys.argv
Python sys.argv module
sys module provides access to any command-line arguments via sys.argv
Python sys module stores the command line arguments into a list, we can access it
using sys.argv.
This is very useful and simple way to read command line arguments as String.
The names "argc" and "argv" stand for "argument count" and "argument vector,“
The argv variable contains an array of strings consisting of each argument from the
command line while the argc variable contains the number of arguments entered.i.e., the
number of items in the sys.argv list.
4 uniform(a, b) :- This function is used to generate a floating point random number between the
numbers mentioned in its arguments. It takes two arguments, lower limit(included in generation)
and upper limit(not included in generation).
>>> import random
>>> random.uniform(5,10)
6.828444584562927
One of the must properties of random numbers is that they should be reproducible. When you
put same seed, you get the same pattern of random numbers.
Ex >>> import random
>>> import random >>> random.seed(4)
>>> random.seed(3) >>> random.randint(1,100)
>>> random.random() 31
0.23796462709189137 >>> random.seed(4)
>>> random.seed(3) >>> random.randint(1,100)
>>> random.random() 31
0.23796462709189137
12. Platform module
# to know your operting system
>>> import platform
>>> platform.system()
'Windows'
13. Statistics Module:
The statistics module provides functions to mathematical statistics of numeric data. The
following popular statistical functions are defined in this module.
1. mean() :
The mean() method calculates the arithmetic mean of the numbers in a list
Ex :
import statistics
# list of positive integer numbers
datasets = [5, 2, 7, 4, 2, 6, 8]
x = statistics.mean(datasets)
# Printing the mean
print("Mean is :", x)
Output :
Mean is : 4.857142857142857
2. median()
The median() function is used to return the middle value of the numeric data in the list.
Before median, this function will perform sort and then find its middle value
Ex
import statistics
datasets = [3,1,2,5,4]
# Printing median of the
# random data-set
print("Median of data-set is :",statistics.median(datasets))
Output
Median of data-set is : 3
3. mode() function
The mode() function returns the most common data that occurs in the list.
Example
import statistics
# declaring a simple data-set consisting of real valued positive integers.
dataset =[2, 4, 7, 7, 2, 2, 3, 6, 6, 8]
# Printing out the mode of given data-set
print("Calculated Mode % s" % (statistics.mode(dataset)))
Output:
Calculated Mode 2
4. stdev() function
The stdev() function is used to calculate the standard deviation on a given sample which
is available in the form of the list.
Example
import statistics
# creating a simple data - set
sample = [7, 8, 9, 10, 11]
# Prints standard deviation
print("Standard Deviation of sample is % s " % (statistics.stdev(sample)))
Output:
Standard Deviation of sample is 1.5811388300841898
4. variance() function
This function is used to calculate the variance on a given sample which is available in the
form of the list.
Example
import statistics
datasets = [4, -5, 6, 6, 9, 4, 5, -2]
# Printing median of the
# random data-set
print("standard variance of data-set is :",statistics.variance(datasets))
Output
standard variance of data-set is : 21.125
14. datetime module
Python has a module named datetime to work with dates and times.
1. How to Get Current Date and Time:
import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
Output:
2020-06-15 12:25:54.193616
Here, we have imported datetime module using import datetime statement.
One of the classes defined in the datetime module is datetime class.
We then used now() method to create a datetime object containing the current local date and
time.
2. Get Current Date:
import datetime
date_object = datetime.date.today()
print(date_object)
Output:
2020-06-15
In this program, we have used today() method defined in the date class to get a date object
containing the current local date.
Output:
Current year: 2020
Current month: 6
Current day: 16
2. datetime.time class
A time object instantiated from the time class represents the local time.
Time object to represent time:
from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(11, 34, 56)
print("b =", b) Output:
The first three arguments year, month and day in the datetime() constructor are
mandatory.
4. Datetime.timedelta:
A timedelta object represents the difference between two dates or times.
from datetime import datetime, date
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
print("type of t3 =", type(t3))
Output:
t3 = 201 days, 0:00:00
type of t3 = <class 'datetime.timedelta'>
Output:
from datetime import datetime
date_string = 21 June, 2018
date_string = "21 June, 2018"
date_object = 2018-06-21 00:00:00
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)
Here , %d, %B and %Y format codes are used for day, month(full name) and year
respectively.
15. Regular Expressions:
Introduction
The regular expressions can be defined as the sequence of characters which are
used to search for a pattern in a string.
It is extremely useful for extracting information from text such as code, files, log,
spreadsheets or even documents.
While using the regular expression the first thing is to recognize is that everything
is a character, and we are writing patterns to match a specific sequence of
characters also referred as string.
^a...s$
The above pattern defines a RegEx pattern.
The pattern is: any five letter string starting with a and ending with s.
Regex Functions
The following regex functions are used in the python.
1. re.match():
This method matches the regex pattern in the string .It returns true if a match is
found in the string otherwise it returns false.
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
ex:
>>> result=re.split('i','Analytics information',maxsplit=3)
>>> result
['Analyt', 'cs ', 'nformat', 'on']
5. re.sub(pattern, repl, string):
It helps to search a pattern and replace with a new sub string. If the pattern is
not found, string is returned unchanged.
Ex;
import re
result=re.sub('India','the World','AV is largest Analytics community of India')
result
Output: 'AV is largest Analytics community of the World'
2. Special Symbols and Characters:
Forming a regular expression
A regular expression can be formed by using the mix of meta-characters, special
sequences, and sets.
1. Meta-Characters
Metacharacter is a character with the specified meaning.
EX:
import re
match=re.match('[abc]','a')
if match:
print("matched")
else:
print("not matched") import re
match=re.match('[^a-e]','a')
if match:
import re print("matched")
match=re.match('[a-e]','a') else:
if match: print("not matched")
print("matched")
else:
print("not matched")
Ex:
import re
match=re.match('..',‘a')
if match:
print("matched")
else:
print("not matched“)
Output: not matched
import re
match=re.match('..','ac')
if match:
print("matched")
else:
print("not matched")
Output: matched
Ex:
import re
match=re.match('^a','ba')
if match:
print("matched")
else:
print("not matched")
For example, If we consider a dog as an object then its properties would be- his color, his
breed, his name, his weight, etc. And his behavior/function would be walking, barking, playing,
etc.
Another example- a car can be an object. If we consider the car as an object then its
properties would be – its color, its model, its price, its brand, etc. And its behavior/function
would be acceleration, slowing down, gear change.
In a similar way, POP requires a certain procedure of steps. A procedural program
consists of functions. This means that in the POP approach the program is divided into
functions, which are specific to different tasks. These functions are arranged in a specific
sequence and the control of the program flows sequentially.
Another important thing is that in procedure-oriented programming all the functions have
access to all the data, which implies a lack of security. Suppose you want to secure the
credentials or any other critical information from the world. Then the procedural approach fails
to provide you that security. For this OOP helps you with one of its amazing functionality
known as Encapsulation, which allows us to hide data.
Programming languages like C, Pascal and BASIC use the procedural approach whereas
Java, Python, JavaScript, PHP, Scala, and C++ are the main languages that provide the Object-
oriented approach.
17.Python OOPs concept
1. Class
2. Object
3. Method
4. Inheritance
5. Data Abstraction
6. Encapsulation
7. Polymorphism
1. Class :
class is a collection of objects. Unlike the primitive data structures, classes are data
structures that the user defines. They make the code more manageable.
How to create Class in Python:
Like function definitions begin with the keyword def, in Python, we define a class using
the keyword class.
The first string is called docstring and has a brief description about the class. Although
not mandatory, this is recommended.
Syntax
class class_name:
class body
We define a class with a keyword “class” following the class_name and semicolon. And we
consider everything you write under this after using indentation as its body.
Ex:
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions..
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello‘)
print(MyClass.a)
print(MyClass.func)
print(MyClass.__doc__)
There are also special attributes in it that begins with double underscores (__). For example,
__doc__ gives us the docstring of that class.
2. Objects:
Python is an object oriented programming language.
Object is simply a collection of data (variables) and methods (functions) that act on those
We can think of class as a sketch (prototype) of a house. It contains all the details about
we can create many objects from a class. An object is also called an instance of a class
When we define a class only the description or a blueprint of the object is created.
There is no memory allocation until we create its object. The objector instance contains
Syntax
Ex
ob = MyClass()
This will create a new instance object named ob. We can access attributes of objects using
the object name prefix.
Ex:
class MyClass:
"This is my second class"
a = 10
ob = MyClass() # creating object of a class
print(ob.a)
# Output: 10
We can access attributes of objects using the object name prefix.
Attributes may be data or method. Method of an object are corresponding functions of that
class. Any function object that is a class attribute defines a method for objects of that class.
This means to say, since MyClass.func is a function object (attribute of class), ob.func will be
a method object.
3. Methods
Objects can also contain methods. Methods in objects are functions that belong to the object
Let us create a method in the Person class:
Ex: Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age): Output: Hello my name is John
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class.
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:
Output:
John Doe
Mike Olsen
Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its
parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to
create a new object.
When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.
Note: The child's __init__() function overrides the inheritance of the parent's __init__()
To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__()
function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function.
Example:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe") Output:
John Doe
x.printname()
Mike
Olsen
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
x.printname()
Use the super() Function
Python also has a super() function that will make the child class inherit all the methods
and properties from its parent:
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, we do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.
Example:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
Output:
def __init__(self, fname, lname, year):
Welcome Mike Olsen to the class of 2019
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
Two built-in functions isinstance() and issubclass() are used to check inheritances.
Function isinstance() returns True if the object is an instance of the class or other classes
derived from it. Each and every class in Python inherits from the base class object.
Example: a=issubclass(Student,Person)
b=isinstance(x,Person) print(a)
print(b) f=issubclass(Person,Student)
c=isinstance(x,Student) print(f)
print(c)
d=isinstance(x,object)
print(d) Output: Output:
True True
e=isinstance(x,int) True False
print(e) True
False
Multiple Inheritance in Python
In Python., like C++, a class can be derived from more than one base classes. This is
called multiple inheritance.
In multiple inheritance, the features of all the base classes are inherited into the derived
class.
The syntax for multiple inheritance is similar to single inheritance.
Example
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
1. Data abstraction:
It refers to the act of representing essential features without including the background
details and explanations. i.e., Abstraction is the process of hiding the real
implementation of an application from the user and emphasizing only on how to use the
application.
Consider the example of a switchboard, you can only press certain switches according
to your requirement. What is happening inside, how it is happening, you need not
know.
An abstract class is created by importing a class named 'ABC' from the 'abc' module and
inheriting the 'ABC' class.
abstract methods should not contain any implementation. So, we can define abstract methods
using the 'pass' statement'
Example
from abc import ABC
class Shape(ABC): #abstract class
def calculate_area(self): #abstract method
pass
class Rectangle(Shape): # normal class
length = 5
breadth = 3
def calculate_area(self): #normal method
return self.length * self.breadth
class Circle(Shape):
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
rec = Rectangle() #object created for the class 'Rectangle'
cir = Circle() #object created for the class 'Circle'
print("Area of a rectangle:", rec.calculate_area()) #call to 'calculate_area' method defined
inside the class 'Rectangle'
print("Area of a circle:", cir.calculate_area()) #call to 'calculate_area' method defined
inside the class 'Circle'.
Output:
Area of a rectangle: 15
Area of a circle: 50.24
encapsulation focuses upon the implementation that gives rise to this behaviour.
In Python, Encapsulation can be achieved by declaring the data members of a class either as
private or protected.
In Python, 'Private' , 'Protected' and ‘public’ are called Access Modifiers, as they modify the
access of variables or methods defined in a class.
The access modifiers supported are:
1. Private:
A private variable can only be accessed by a method that is of the same class and not
outside of the class. These variables start with __ (private members are preceded by two
underscores).
For Example:
__engineno, __modelname
A private method can be called by a method of the same class. These methods start
with __.
For Example:
def __setmodelname()
In the below example, 'length' and 'breadth' are the two private variables declared and can
be accessed within the class 'Rectangle‘.
class Rectangle:
__length = 0 #private variable
__breadth = 0 #private variable
def __init__(self): #constructor
self. __length = 5
self.__breadth = 3 #printing values of the private variable within the class
print(self.__length)
print(self.__breadth)
rec = Rectangle() #object created for the class 'Rectangle'
#printing values of the private variable outside the class using the object created
for the class 'Rectangle'
print(rec.__length)
print(rec.__breadth)
output
5
3
AttributeError: 'Rectangle' object has no attribute ‘__length'
Since we have accessed private variables in the main() method, i.e., outside the class
'Rectangle', we got an error.
Hence in the above program, Encapsulation is achieved using the private variables 'length' and
'breadth'.
2. protected :
In Python, Protected members can be accessed within the class in which they are
defined and also within the derived classes.
protected members are preceded by a single underscore. In the below example, ‘_length'
and ‘_breadth' are the two protected variables defined inside the class 'Shape'.
When we try to access protected variables in the derived class, we got output. But, in the
main() method, we got an error.
Hence in the above example, Encapsulation is achieved using the protected variables 'length'
and 'breadth'.
3. Public:
A public variable can be accessed from anywhere.
A public method can be called from anywhere.
There is no specific word or character to represent the public access modifier. Anything
that does not have a __ is a public variable or method.
Ex:
class MyClass:
num = 10
def add(self, a):
sum = self.num + a
print(sum)
Output:
ob = MyClass()
10
ob.add(20)
20
print(ob.num)
7. Polymorphism
polymorphism refers to the ability of a real-time object to represent itself in many
forms.
For example. When you are at college, you act as a student. When are at your home, you
act like a child. You are a single person, but you represent yourself differently in different
places.
Polymorphism is used in Python programs when you have commonly named methods in
two or more classes or subclasses.
It allows these methods to use objects of different types at different times. So, it provides
flexibility, using which a code can be extended and easily maintained over time.
Polymorphism in Built-In Method
In the below-given example, the built-in method 'len' processes two different objects, one
being a list & another a string.
#printing length of two different objects
print(len([2, 4, 6, 8, 9]))
print(len("FACE Prep"))
Output:
5
9
Here, the method 'len' prints the length of two different objects. In the first print statement,
it prints the length of a list object and in the second, it prints the length of a string object.
So, polymorphism is achieved using the built-in method 'len'.
Polymorphism in User-Defined Method
In the below diagram, 'calculate_area' is the user-defined method created with different
operations in both the classes 'Rectangle' and 'Circle'.
class Rectangle:
length = 5
breadth = 3
output
def calculate_area(self):
Area of a rectangle: 15
return self.length * self.breadth
Area of a circle: 50.24
class Circle:
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
rec = Rectangle() #object created for the class 'Rectangle'
cir = Circle() #object created for the class 'Circle'
print("Area of a rectangle:", rec.calculate_area())
#call to 'calculate_area' method defined
inside the class 'Rectangle'
print("Area of a circle:", cir.calculate_area())
Here, polymorphism is achieved using the method 'calculate_area' that works differently in
#call to 'calculate_area' method defined
different classes.
Constructors in Python:
Constructors are special methods that are defined inside a class. They are invoked
when an object is created for the class.
They also verify whether there are enough variables and methods available for an object
to perform a task defined in the class.
Syntax of constructor declaration :
Similar to Functions, a constructor is defined with the keyword 'def' followed by a constructor
def __init__(self):
A constructor always has the name 'init' and the name is prefixed, suffixed with a
double underscore(__).
The first parameter of the constructor must be 'self'. This parameter is used to store the
In Python the __init__() method is called the constructor and is always called when an
object is created.
Types of constructors :
In Python, we have two types of constructors.
1) Default constructor
2) Parameterized constructor
1.default constructor :
The default constructor does not have any parameters other than 'self'. It will not accept any
arguments other than the object created for the class in which it is defined.
class Employee:
age = 0 #class variable
def __init__(self): # default constructor used to initialize 'age' with the value 22
self.age = 22
#main() method
John = Employee()
#creating object (John) for the class 'Employee'. Once the object is created, the Python inte
rpreter calls the default constructor
print(John.age) # printing the value stored in the variable 'age' using the object 'John‘
Output
22
If the user did not define a constructor inside a class, then the Python interpreter implicitly
defines a default constructor that does not do any operations.
We can pass arguments while creating an object and those arguments get stored in a
parameterized constructor.
class Employee:
output
def __init__(self, age, salary):
John age: 22
self.age1 = age
John salary: 20000
self.salary1 = salary
Alex age: 30
#main() method
Alex salary: 27000
John = Employee(22, 20000)
Alex = Employee(30, 27000)
print("John age:", John.age1)
print("John salary:", John.salary1)
print("Alex age:", Alex.age1)
print("Alex salary:", Alex.salary1)
Here, the values 22 and 20000 are passed as the arguments during the object creation to the
parameterized constructor defined inside the class 'Employee'.
These values get stored in the parameters 'age' and 'salary'. Later, both the values get
assigned to the variables 'age1' and 'salary1'.
We can also create another object for the same class and pass the arguments.
2. parameterized constructor :
constructor with parameters is known as parameterized constructor. The parameterized
constructor take its first argument as a reference to the instance being constructed known
as self and the rest of the arguments are provided by the programmer.
This constructor accepts and stores arguments passed from the main() method during
object creation
Ex
class Employee:
def __init__(self, age, salary):
self.age1 = age
self.salary1 = salary
#main() method
John = Employee(22, 20000) #passing arguments to the parameterized constructor
Output
print(John.age1)
22
print(John.salary1)
20000
Example of parameterized constructor :
class Addition:
def __init__(self, f, s): # parameterized constructor
self.first = f Output :
self.second = s
def display(self): First number = 1000
print("First number = " + str(self.first)) Second number = 2000
print("Second number = " + str(self.second)) Addition of two numbers = 3000
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
obj = Addition(1000, 2000) # creating object of the class
obj.calculate() # perform Addition
obj.display() # display result
Python - Built-in Class Attributes
We can access the built-in class attributes using the . operator.
Following are the built-in class attributes.
1. __doc__ class attribute
In the following Python program we are creating Awesome class with documentation
Program
class Awesome: # class
'This is a sample class called Awesome.'
def __init__(self):
print("Hello from __init__ method.") # class built-in attribute
print(Awesome.__doc__)
Output
This is a sample class called Awesome.
2. __name__ class attribute
In the following example we are printing the name of the class
Program
class Awesome:
'This is a sample class called Awesome.'
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__name__)
Output
Awesome
3. _module__ class attribute
In the following example we are printing the module of the class
Program
class Awesome:
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__module__)
Output
__main__
4. __bases__ class attribute
In the following example we are printing the bases of the class.
program
class Awesome:
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__bases__)
Output
(<class 'object'>,)
5. __dict__ class attribute
In the following example we are printing the dict of the class.
Program
class Awesome:
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__dict__)
Output
{'__module__': '__main__', '__init__': <function Awesome.__init__ at 0x7f16e62c27a0>,
'__dict__': <attribute '__dict__' of 'Awesome' objects>, '__weakref__': <attribute '__weakref__'
of 'Awesome' objects>, '__doc__': None}
Method overriding:
Overriding is the property of a class to change the implementation of a method provided
by one of its base classes.
The method overriding means creating two methods with the same name but differ in
the programming logic.
The concept of Method overriding allows us to change or override the Parent Class
function in the Child Class.
In python, inheritance involves a relationship between parent and child classes.
Whenever both the classes contain methods with the same name and arguments or
parameters it is certain that one of the methods will override the other method during
execution. The method that will be executed depends on the object.
If the child class object calls the method, the child class method will override the parent class
method. Otherwise, if the parent class object calls the method, the parent class method will be
executed.
Example
class Animal():
def sound(self, a): output
print("This is parent class") Dogs bark
class Dogs(Animal):
def sound(self):
print("Dogs bark")
d1 = Dogs()
d1.sound()
In the above example, the class Dogs and its parent class Animal have methods with the same
name sound. When the object d1 of the class Dogs calls this method, then the method of the
child class Dogs gets called, not that of the parent class. Thus, the method of the child class
overrides the method of the parent class when called by an object of the child class. This is
GUI Programming:
Introduction:
What Is A Graphical User Interface (GUI)?
Graphical User Interface (GUI) is nothing but a desktop application which helps you to
interact with the computers. They are used to perform different tasks in the desktops,
laptops and other electronic devices.
GUI apps like Text-Editors are used to create, read, update and delete different types of
files.
GUI apps like Sudoku, Chess and Solitaire are games which you can play.
2. JPython: It is the Python platform for Java that is providing Python scripts seamless
access o Java class Libraries for the local machine.
There are many other interfaces(Kivy ,Python QT) available for GUI. Among all of
these, Tkinter is preferred by a lot of learners and developers just because of how simple
and easy it is.
What Are Tcl, Tk, and Tkinter?
Due to Tk's popularity, it has been ported to a variety of other scripting languages,
including Perl (Perl/Tk), Ruby (Ruby/Tk), and Python (Tkinter).
4. Label is used to insert some objects into the window. Here, we are adding a Label with
some text.
pack() attribute of the widget is used to display the widget in a size it requires.
import tkinter
window = tkinter.Tk()
window.title("GUI")
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()
As soon as you run the application, you’ll see the position of the Tkinter window is at the
north-west position of the screen and the size of the window is also small as shown in the output.
Tkinter window using geometry method.
import tkinter
window = tkinter.Tk()
window.title("GUI")
window.geometry('500x500')
label = tkinter.Label(window, text = "Hello World!").pack()
window.mainloop()
After running the application, you’ll see that the size of the Tkinter window is changed, but the
position on the screen is same.
geometry manager
In order to organize or arrange or place all the widgets in the parent window, Tkinter
provides us the geometric configuration of the widgets.
It is important to note here that each window and Frame in your application is allowed
to use only one geometry manager.
Also, different frames can use different geometry managers, even if they're already
assigned to a frame or window using another geometry manager.
import tkinter
top = tkinter.Tk()
C.pack()
top.mainloop()
3. Scale widget:
Scale widget is used to implement the graphical slider to the python application so that
the user can slide through the range of values shown on the slider and select the one among
them.
We can control the minimum and maximum values along with the resolution of the scale.
Syntax
w = Scale(top, options)
A list of possible options is given below:
from_: It is used to represent one end of the widget range.
to: It represents a float or integer value that specifies the other end of the
range represented by the scale.
orient: It can be set to horizontal or vertical depending upon the type of the scale.
bd: The border size of the widget. The default is 2 pixel.
bg: The background color of the widget.
font: The font type of the widget text.
fg: The foreground color of the text
Ex:
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=100)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()
4. Label:
The Label is used to specify the container box where we can place the text or images. This
widget is used to provide the message to the user about other widgets used in the python
application.
There are the various options which can be specified to configure the text or the part of the
text shown in the Label.
Syntax:
w = Label (master, options)
•master is the parameter used to represent the parent window.
•There are number of options which are used to change the format of the widget.
bg: to set he normal background color.
bg to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the button.
width: to set the width of the button.
height” to set the height of the button.
Ex:
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
relief
Specifies the appearance of a
decorative border around the
label. The default is FLAT.
5. Checkbutton:
This widget is used to display a number of options to a user as toggle buttons. The
user can then select one or more options by clicking the button corresponding to each
option. (similar to HTML checkbox input)
Ex: checkbutton
from tkinter import *
import messagebox
import tkinter
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue
= 0, height=5, width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue
= 0, height=5, width = 20)
C1.pack() C2.pack() top.mainloop()
6. Entry
The Entry widget is used to provide the single line text-box to the user to accept
a value from the user.
If you want to display multiple lines of text that can be edited, then you should
use the Text widget.
If you want to display one or more lines of text that cannot be modified by the
user, then you should use the Label widget.
8. Listbox:
The Listbox widget is used to display a list of items from which a
user can select a number of items.
9. Menu:
The goal of this widget is to allow us to create all kinds of menus
that can be used by our applications. The core functionality provides
ways to create three menu types: pop-up, top-level and pull-down.
Ex: frame widget
Ex: Listbox widget
root = Tk()
var = StringVar()
label.pack()
root.mainloop()
Ex: Message box widget
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg = messagebox.showinfo( “Say Hello", "Hello World")
B = Button(top, text = “Say Hello", command = helloCallBack)
B.place(x = 100,y = 100)
top.mainloop()
13. Radiobutton:
Set of buttons of which only one can be "pressed" (similar to
HTML radio input)
14. Scrollbar:
The scrollbar widget is used to scroll down the content of the
other widgets like listbox, text, and canvas. However, we
can also create the horizontal scrollbars to the Entry widget.
15. Text
It is used to show the text data on the Python application.
However, Tkinter provides us the Entry widget which is used
to implement the single line text box.
The Text widget is used to display the multi-line
formatted text with various styles and attributes.
The Text widget is used to provide the text editor to the
Ex: Radio button
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text=“C", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
label = Label(root)
label.pack()
root.mainloop()
Ex: scroll bar:
root = Tk()
scrollbar = Scrollbar(root)
mainloop()
Ex: text
from tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
17. spinbox:
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
Ex:
from tkinter import *
master = Tk()
w = Spinbox(master, from_=0, to=10)
w.pack()
mainloop()