Python UNIT4 Notes
Python UNIT4 Notes
UNIT 4
Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which can contain data and code: data in the form of fields (often known
as attributes or properties), and code, in the form of procedures (often known as methods).
A feature of objects is that an object's own procedures can access and often modify the data
fields of itself (objects have a notion of this or self ). In OOP, computer programs are
designed by making them out of objects that interact with one another. OOP languages are
diverse, but the most popular ones are class-based, meaning that objects
are instances of classes, which also determine their types.
Python is a multi-paradigm programming language. It supports different programming
approaches.
One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
attributes
behavior
The concept of OOP in Python focuses on creating reusable code. This concept is also known
as DRY (Don't Repeat Yourself).
Class
A class is a blueprint for the object.
We can think of class as a sketch of a parrot with labels. It contains all the details about the name,
colors, size etc. Based on these descriptions, we can study about the parrot. Here, a parrot is an
object.
class Parrot:
pass
Here, we use the class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.
Object
An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.
obj = Parrot()
Suppose we have details of parrots. Now, we are going to show how to build the class and
objects of parrots.
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
Output
Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old
In the above program, we created a class with the name Parrot. Then, we define attributes.
The attributes are a characteristic of an object.
These attributes are defined inside the __init__ method of the class. It is the initializer method
that is first run as soon as the object is created.
Then, we create instances of the Parrot class. Here, blu and woo are references (value) to our
new objects.
We can access the class attribute using __class__.species. Class attributes are the same for all
instances of a class. Similarly, we access the instance attributes using blu.name and blu.age.
However, instance attributes are different for every instance of a class.
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.
Example
1. class Employee:
2. def init (self, name, id):
3. self.id = id
4. self.name = name
5.
6. def display(self):
7. print("ID: %d \nName: %s" % (self.id, self.name))
8.
9.
10. emp1 = Employee("John", 101)
11. emp2 = Employee("David", 102)
12.
13. # accessing display() method to print employee 1 information
14.
15. emp1.display()
16.
17. # accessing display() method to print employee 2 information
18. emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
Example
1. class Student:
2. # Constructor - parameterized
3. def __init (self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()
Output:
Example
1. class Student:
2. roll_num = 101
3. name = "Joseph"
4.
5. def display(self):
6. print(self.roll_num,self.name)
7.
8. st = Student()
9. st.display()
Output:
101 Joseph
Inheritance
Inheritance is a way of creating a new class for using details of an existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the existing
class is a base class (or parent class).
# parent class
class Bird:
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Output
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this from
the swim() method.
Again, the child class modified the behavior of the parent class. We can see this from
the whoisThis() method. Furthermore, we extend the functions of the parent class, by
creating a new run() method.
Additionally, we use the super() function inside the __init__() method. This allows us to run
the __init__() method of the parent class inside the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data
from direct modification which is called encapsulation. In Python, we denote private
attributes using underscore as the prefix i.e single _ or double __.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
c.__maxprice = 1000
c.sell()
Output
Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data
types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square,
circle). However we could use the same method to color any shape. This concept is called
Polymorphism.
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
Output
In the above program, we defined two classes Parrot and Penguin. Each of them have a
common fly() method. However, their functions are different.
To use polymorphism, we created a common interface i.e flying_test() function that takes any
object and calls the object's fly() method. Thus, when we passed the blu and peggy objects in
the flying_test() function, it ran effectively.
In Python, you can create a method that can be called in different ways. So, you can have a
method that has zero, one or more number of parameters. Depending on the method
definition, we can call it with zero, one or more arguments.
Given a single method or function, the number of parameters can be specified by you. This
process of calling the same method in different ways is called method overloading.
In the following example, we will overload the area method. If there is no argument then it
returns 0. And, If we have one argument then it returns the square of the value and assumes
you are computing the area of a square. Also, if we have two arguments then it returns the
product of the two values and assumes you are computing the area of a rectangle.
# class
class Compute:
# area method
def area(self, x = None, y = None):
if x != None and y != None:
return x * y
elif x != None:
return x * x
else:
return 0
# object
obj = Compute()
# zero argument
print("Area Value:", obj.area())
# one argument
print("Area Value:", obj.area(4))
# two argument
print("Area Value:", obj.area(3, 5))
Area Value: 0
Area Value: 16
Area Value: 15
# function breathdef
breathe(self):
print("I breathe oxygen.")
# function feed
def feed(self): print("I
eat food.")
# child class
class Herbivorous(Animal):
# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")
herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()
OUTPUT:
I eat only plants. I am vegetarian.
I breathe oxygen.
What
Jain is Operator
College Overloading
of BBA BCA in Python
& Commerce, Belagavi Page 11
The operator overloading in Python means provide extended meaning beyond their predefined
Python Third Chapter Notes - GSM
operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two
strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class
and "str" class. The user can notice that the same inbuilt operator or function is showing different
behaviour for objects of different classes. This process is known as operator overloading.
Example:
Output:
46
JavaTpoint
322
X Y Z X Y Z X Y Z
Suppose the user has two objects which are the physical representation of a user-defined data type
class. The user has to add two objects using the "+" operator, and it gives an error. This is because the
compiler does not know how to add two objects. So, the user has to define the function for using the
operator, and that process is known as "operator overloading". The user can overload all the existing
operators by they cannot create any new operator. Python provides some special functions, or we can
say magic functions for performing operator overloading, which is automatically invoked when it is
associated with that operator. Such as, when the user uses the "+" operator, the magic function
__add__ will automatically invoke in the command where the "+" operator will be defined.
When the user uses the operator on the user-defined data types of class, then a magic function that is
associated with the operator will be invoked automatically. The process of changing the behaviour of
Jain College
the operator is of
asBBA BCAas
simple & Commerce, Belagavi
the behaviour of the function or method defined. Page 12
Python Third Chapter Notes - GSM
The user define methods or functions in the class and the operator works according to that behaviour
defined in the functions. When the user uses the "+" operator, it will change the code of a magic
function, and the user has an extra meaning of the "+" operator.
Python program for simply using the overloading operator for adding two objects.
Example:
1. class example:
2. def __init__(self, X):
3. self.X = X
4.
5. # adding two objects
6. def __add__(self, U):
7. return self.X + U.X
8. object_1 = example( int( input( print ("Please enter the value: "))))
9. object_2 = example( int( input( print ("Please enter the value: "))))
10. print (": ", object_1 + object_2)
11. object_3 = example(str( input( print ("Please enter the value: "))))
12. object_4 = example(str( input( print ("Please enter the value: "))))
13. print (": ", object_3 + object_4)
Output:
ADVERTISEMENT
1. class complex_1:
2. def __init__(self, X, Y):
3. self.X = X
4. self.Y = Y
5.
6. # Now, we will add the two objects
7. def __add__(self, U):
8. return self.X + U.X, self.Y + U.Y
9.
10. Object_1 = complex_1(23, 12)
11. Object_2 = complex_1(21, 22)
12. Object_3 = Object_1 + Object_2
13. print (Object_3)
Output:
(44, 34)
Example:
1. class example_1:
2. def __init__(self, X):
3. self.X = X
4. def __gt__(self, U):
5. if(self.X > U.X):
6. return True
7. else:
8. return False
9. object_1 = example_1(int( input( print ("Please enter the value: "))))
10. object_2 = example_1(int (input( print("Please enter the value: "))))
11. if(object_1 > object_2):
12. print ("The object_1 is greater than object_2")
13. else:
14. print ("The object_2 is greater than object_1")
Jain College of BBA BCA & Commerce, Belagavi Page 14
Output:
Python Third Chapter Notes - GSM
Case 1:
Case 2:
ADVERTISEMENT
Please enter the value: 20
Please enter the value: 31
The object_2 is greater than object_1
Example:
1. class E_1:
2. def __init__(self, X):
3. self.X = X
4. def __lt__(self, U):
5. if(self.X < U.X):
6. return "object_1 is less than object_2"
7. else:
8. return "object_2 is less than object_1"
9. def __eq__(self, U):
10. if(self.X == U.X):
11. return "Both the objects are equal"
12. else:
13. return "Objects are not equal"
14.
15. object_1 = E_1(int( input( print ("Please enter the value: "))))
16. object_2 = E_1(int( input( print ("Please enter the value: "))))
17. print (": ", object_1 < object_2)
18.
19. object_3 = E_1(int( input( print ("Please enter the value: "))))
20. object_4 = E_1(int( input( print ("Please enter the value: "))))
21. print (": ", object_3 == object_4)
Output:
Jain College of BBA BCA & Commerce, Belagavi Page 15
ADVERTISEMENT
Python Third Chapter Notes - GSM
ADVERTISEMENT
Case 1:
Case 2:
+ __add__(self, other)
- __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
| __or__(self, other)
Jain College of BBA BCA & Commerce, Belagavi Page 16
^ __xor__(self, other)
Python Third Chapter Notes - GSM
Comparison Operators:
== __EQ__(SELF, OTHER)
!= __NE__(SELF, OTHER)
Assignment Operators:
-= __ISUB__(SELF, OTHER)
+= __IADD__(SELF, OTHER)
*= __IMUL__(SELF, OTHER)
/= __IDIV__(SELF, OTHER)
%= __IMOD__(SELF, OTHER)
|= __IOR__(SELF, OTHER)
^= __IXOR__(SELF, OTHER)
Jain College of BBA BCA & Commerce, Belagavi Page 17
Unary Operator:
Python Third Chapter Notes - GSM
- __NEG__(SELF, OTHER)
+ __POS__(SELF, OTHER)
~ __INVERT__(SELF, OTHER)
Python Modules
What are modules in Python?
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for example: example.py, is called a module, and its module name
would be example.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
result = a + b
return result
Here, we have defined a function add() inside a module named example. The function takes in two
numbers and returns their sum.
We use the import keyword to do this. To import our previously defined module example, we type
the following in the Python prompt.
Jain College of BBA BCA & Commerce, Belagavi Page 18
Python Third Chapter Notes - GSM
This does not import the names of the functions defined in example directly in the current symbol
table. It only imports the module name example there.
Using the module name we can access the function using the dot . operator. For example:
>>> example.add(4,5.5)
9.5
Python has tons of standard modules. You can check out the full list of Python standard modules and
their use cases. These files are in the Lib directory inside the location where you installed Python.
Standard modules can be imported the same way as we import our user-defined modules.
There are various ways to import modules. They are listed below..
import math
print("The value of pi is", math.pi)
import math as m
print("The value of pi is", m.pi)
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is the
correct implementation.
Jain College of BBA BCA & Commerce, Belagavi Page 19
Python Third Chapter Notes - GSM
It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file should
be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as special
character. For example, if there is \temp in the file address, then \t is treated as the tab character and
error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any
special characters. The r can be ignored if the file is in same directory and address is not being placed.
# Open function to open the file "MyFile1.txt" #
file1 = open("MyFile.txt","a")
# store its reference in the variable file1 #
open(r"D:\Text\MyFile2.txt","w+")
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at the time
when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()
# Opening and Closing a file "MyFile.txt" #
Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
2. writelines() : For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
File_object.read([n])
2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most
n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
3. readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes
# Program to show various ways to read and #
write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
open("myfile.txt","r+")
Jain College of BBA BCA & Commerce, Belagavi Page 21
Python Third Chapter Notes - GSM
file1.seek(0)
file1.seek(0)
# readlines function
print "Output of Readlines function is " print
file1.readlines()
print file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Appending to a file
file1 = open("myfile.txt","w")
file1.close()
# Append-adds at last
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
file1.readlines()
print file1.close()
# Write-Overwrites
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
file1.readlines()
print file1.close()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
>>> len(sys.argv)
Output
1
Jain College of BBA BCA & Commerce, Belagavi Page 24
Python Third Chapter Notes - GSM
copyright
A string containing the copyright pertaining to the Python interpreter.
>>> sys.copyright
Output:
path
A list of strings that specifies the search path for modules. Initialized from the
environment variable $PYTHONPATH, or an installation-dependent default.
>>> sys.path
['', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37- 32\\python37.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37- 32\\lib\\site-packages']
>
platform
This string contains a platform identifier, e.g. 'sunos5' or 'linux1'. This can be used to
append platform-specific components to path, for instance.
prefix
>>> sys.platform
OUTPUT
'win32'
REGULAR EXPRESSION
A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For
example,
^a...s$
The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and
ending with s.
A pattern defined using RegEx can be used to match against a string.
pattern = '^a...s$'
test_string = 'abyss'
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
Here, we used re.match() function to search pattern within the test_string. The method returns a
match object if the search is successful. If not, it returns None.
There are other several functions defined in the re module to work with RegEx. Before we explore
that, let's learn about regular expressions themselves.
MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a listof
metacharacters:
[] . ^ $ * + ? {} () \ |
[] - Square brackets
You can complement (invert) the character set by using caret ^ symbol at the start of a square-
bracket.
. - Period
^ - Caret
The caret symbol ^ is used to check if a string starts with a certain character.
$ - Dollar
The dollar symbol $ is used to check if a string ends with a certain character.
* - Star
The star symbol * matches zero or more occurrences of the pattern left to it.
+ - Plus
The plus symbol + matches one or more occurrences of the pattern left to it.
? - Question Mark
The question mark symbol ? matches zero or one occurrence of the pattern left to it.
{} - Braces
Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left to it.
| - Alternation
() - Group
Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz
\ - Backslash
Backlash \ is used to escape various characters including all metacharacters. For example,
\$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine in a
special way.
If you are unsure if a character has special meaning or not, you can put \ in front of it. This makes
sure the character is not treated in a special way.
Special Sequences
Special sequences make commonly used patterns easier to write. Here's a list of special
sequences:
\B - Opposite of \b. Matches if the specified characters are not at the beginning or end of a word.
\S- Matches where a string contains any non-whitespace character. Equivalent to [^ \t\n\r\
f\v].
Tip: To build and test regular expressions, you can use RegEx tester tools such as regex101. This
tool not only helps you in creating regular expressions, but it also helps you learn it.
Now you understand the basics of RegEx, let's discuss how to use RegEx in your Python code.
Python RegEx
Python has a module named re to work with regular expressions. To use it, we need to import the
module.
import re
The module defines several functions and constants to work with RegEx.
re.findall()
The re.findall() method returns a list of strings containing all matches.
Example 1: re.findall()
# Program to extract numbers from a stringimport
re
pattern = '\d+'
print(result)
re.split()
The re.split method splits the string where there is a match and returns a list of strings wherethe
splits have occurred.
Example 2: re.split()
import re
pattern = '\d+'
print(result)
You can pass maxsplit argument to the re.split() method. It's the maximum number of
splits that will occur.
import re
By the way, the default value of maxsplit is 0; meaning all possible splits.
re.sub()
The syntax of re.sub() is:
re.sub(pattern, replace, string)
The method returns a string where matched occurrences are replaced with the content of replace
variable.
Example 3: re.sub()
# Program to remove all whitespaces
replace = ''
print(new_string)
# Output: abc12de23f456
You can pass count as a fourth parameter to the re.sub() method. If omited, it results to 0. This
will replace all occurrences.
import re# multiline string
pattern = '\s+'
replace = ''
print(new_string)
re.subn()
The re.subn() is similar to re.sub() expect it returns a tuple of 2 items containing the new
string and the number of substitutions made.
Example 4: re.subn()
# Program to remove all whitespaces
replace = ''
print(new_string)
# Output: ('abc12de23f456', 4)
re.search()
The re.search() method takes two arguments: a pattern and a string. The method looks for the
Jain College of BBA BCA & Commerce, Belagavi Page 9
Python Fourth Chapter Notes-GSM
first location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
match = re.search(pattern, str)
Example 5: re.search()
import re
if match:
else:
Match object
You can get methods and attributes of a match object using dir() function.
Some of the commonly used methods and attributes of match objects are:
match.group()
The group() method returns the part of the string where there is a match.
string = '39801 356, 2102 1111'# Three digit number followed by space followed
by two digit
if match:
print(match.group())
else:
Jain College of BBA BCA & Commerce, Belagavi Page 10
Python Fourth Chapter Notes-GSM
Our pattern (\d{3}) (\d{2}) has two subgroups (\d{3}) and (\d{2}). You can get the
part of the string of these parenthesized subgroups. Here's how:
>>> match.group(1)
'801'
>>> match.group(2)
'35'
>>> match.group(1, 2)
('801', '35')
>>> match.groups()
('801', '35')
>>> match.end()
The span() function returns a tuple containing start and end index of the matched part.
>>> match.span()
(2, 8)
We have covered all commonly used methods defined in the re module. If you want to learn more,
Backlash \ is used to escape various characters including all metacharacters. However, using r
prefix makes \ treat as a normal character.