0% found this document useful (0 votes)
0 views

1722964411-Python_Unit_5

The document provides an overview of Python programming, focusing on the use of the os.mkfifo() method to create named pipes and the principles of Object-Oriented Programming (OOP). It explains key concepts such as classes, objects, inheritance, polymorphism, and encapsulation, emphasizing how OOP models real-world entities. Additionally, it discusses the importance of classes in organizing complex data and includes examples of class and instance attributes, as well as methods in Python.

Uploaded by

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

1722964411-Python_Unit_5

The document provides an overview of Python programming, focusing on the use of the os.mkfifo() method to create named pipes and the principles of Object-Oriented Programming (OOP). It explains key concepts such as classes, objects, inheritance, polymorphism, and encapsulation, emphasizing how OOP models real-world entities. Additionally, it discusses the importance of classes in organizing complex data and includes examples of class and instance attributes, as well as methods in Python.

Uploaded by

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

PYTHON PROGRAMMING KG College of Arts and Science

Code: Use of os.mkfifo() method

# Python3 program to explain os.mkfifo() method

# importing os module
import os

# Path
path = "./mypipe"

# Mode of the FIFO (a named pipe)


# to be created
mode = 0o600

# Create a FIFO named path


# with the specified mode
# using os.mkfifo() method
os.mkfifo(path, mode)

print("FIFO named '% s' is created successfully." % path)


Output:
FIFO named './mypipe' is created successfully.

END OF UNIT-IV

UNIT V
OBJECT ORIENTED FEATURES: Classes Principles of Object Orientation - Creating
Classes - Instance Methods - File Organization - Special Methods - Class Variables Inheritance
Polymorphism - Type Identification - Simple Character Matches - Special Characters -
Character Classes Quantifiers - Dot Character - Greedy Matches Grouping - Matching at
Beginning or End - Match Objects Substituting - Splitting a String - Compiling Regular
Expressions. (10)

5. PYTHON OBJECT ORIENTED FEATURES :

In Python, Object-Oriented Programming (OOPs) is a programming paradigm that uses


objects and classes in programming. It aims to implement real-world entities like inheritance,
polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind
the data and the functions that work on that together as a single unit so that no other part of the
code can access this data.
Object-Oriented Programming (OOP) is a method of structuring a program by
bundling related properties and behaviors into individual objects. Conceptually, objects are like
Page 114
PYTHON PROGRAMMING KG College of Arts and Science
the components of a system. Think of a program as a factory assembly line of sorts. At each step
of the assembly line a system component processes some material, ultimately transforming raw
material into a finished product. An object contains data, like the raw or preprocessed materials
at each step on an assembly line, and behavior, like the action each assembly line component
performs.
What is Object-Oriented Programming in Python?
Object-oriented programming is a programming paradigm that provides a means of
structuring programs so that properties and behaviors are bundled into individual objects. For
instance, an object could represent a person with properties like a name, age, and address
and behaviors such as walking, talking, breathing, and running. Or it could represent
an email with properties like a recipient list, subject, and body and behaviors like adding
attachments and sending. Put another way, object-oriented programming is an approach for
modeling concrete, real-world things, like cars, as well as relations between things, like
companies and employees, students and teachers, and so on. OOP models real-world entities as
software objects that have some data associated with them and can perform certain functions.
Another common programming paradigm is procedural programming, which structures a
program like a recipe in that it provides a set of steps, in the form of functions and code blocks,
that flow sequentially in order to complete a task. The key takeaway is that objects are at the
center of object-oriented programming in Python, not only representing the data, as in procedural
programming, but in the overall structure of the program as well.

5.1 Main Concepts of Object-Oriented Programming (OOPs) :


Class
Objects
Polymorphism
Encapsulation
Inheritance

What is the need for a Class in Python ?


Primitive data structures like numbers, strings, and lists are designed to represent simple
pieces of information, such as the cost of an apple, the name of a poem, or your favorite colors,
respectively. What if you want to represent something more complex?
For example, e a ac e ee a ga a . Need e e ba c
information about each employee, such as their name, age, position, and the year they started
working.
Page 115
PYTHON PROGRAMMING KG College of Arts and Science
One way to do this is to represent each employee as a list:

kirk = ["James Kirk", 34, "Captain", 2265]


spock = ["Spock", 35, "Science Officer", 2254]
mccoy = ["Leonard McCoy", "Chief Medical Officer", 2266]

There are a number of issues with this approach.


First, it can make larger code files more difficult to manage. If you reference kirk[0] several
lines away from where the kirk list is declared, will you remember that the element with
index 0 ee ee a e?
Second, it can introduce errors if not every employee has the same number of elements in the list.
In the mccoy list above, the age is missing, so mccoy[1] will return "Chief Medical
Officer" ead f D . McC age.
A great way to make this type of code more manageable and more maintainable is to use classes.

5.2 What is a Class ?


A class is a collection of objects. class, which is like a blueprint for creating an object. A
class contains the blueprints or the prototype from which the objects are being created. It is a
logical entity that contains some attributes and methods.
T de a d e eed f c ea g a c a e c de a e a e, e a a ed
to track the number of dogs that may have different attributes like breed, age. If a list is used,
the first element could be the d g b eed e e ec d e e e c d e e e age.
Le e e e a e 100 d ffe e d g , e d c ee e
supposed to be which? What if you wanted to add other properties to these dogs? This lacks
organization and it e e ac eed f c a e .

Some points on Python class:


Classes are created by keyword class.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

Class Definition Syntax:


class ClassName:
# Statement-1
.
.
# Statement-N
Example: Creating an empty Class in Python
P 3 ga de a e def gaca
class Dog:
pass

In the above example, have created a class named dog using the class keyword.

How to Define a Class


All class definitions start with the class keyword, which is followed by the name of the class
a dac . A c de a de ed be e c a def c de ed a f e c a
body.
He e a example of a Dog class:

Page 116
PYTHON PROGRAMMING KG College of Arts and Science
class Dog:
pass

The body of the Dog class consists of a single statement: the pass keyword. pass is often used as
a placeholder indicating where code will eventually go. It allows you to run this code without
Python throwing an error.

OBJECTS :

The object is an entity that has a state and behavior associated with it. It may be any real -world
object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers,
even arrays, and dictionaries, are all objects. More specifically, any single integer or any single
g a b ec . T e be 12 a b ec , e g He , d a b ec , a
an object that can hold other objects, and so on.
An object consists of : (SBI)
State: It is represented by the attributes of an object. It also reflects the properties of an
object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
To understand the State, Behavior, and Identity let us take the example of the class dog
(explained above).
The identity can be considered as the name of the dog.
State or Attributes can be considered as the breed, age, or color of the dog.
The behavior can be considered as to whether the dog is eating or sleeping.

#Example: Creating an object

obj = Dog()

This will create an object named obj of the class Dog defined above. Before diving deep into
objects and class let us understand some basic keywords that used while working with objects
and classes.
The self
1. Class methods must have an extra first parameter in the method definition. Value for this
parameter when the method is called , Python provides it.
2. If we have a method that takes no arguments, then we still have to have one argument.
3. This is similar to this pointer in C++ and this reference in Java.
When call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) this is all the special self is
about.
The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object
of a class is instantiated. The method is useful to do any initialization you want to do with your
object.
Now let us define a class and create some objects using the self and __init__ method.
Example 1: Creating a class and object with class and instance attributes
P 3
class Dog:
# class attribute
attr1 = "mammal"
Page 117
PYTHON PROGRAMMING KG College of Arts and Science
# Instance attribute
def __init__(self, name):
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class attributes
print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))
# Accessing instance attributes
print("My name is {}".format(Rodger.name))
print("My name is {}".format(Tommy.name))

Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
#Example 2: Creating Class and objects with methods
class Dog:

# class attribute
attr1 = "mammal"

# Instance attribute
def __init__(self, name):
self.name = name

def speak(self):
print("My name is {}".format(self.name))

# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class methods
Rodger.speak()
Tommy.speak()

Output
My name is Rodger
My name is Tommy

Classes vs Instances :
Classes are used to create user-defined data structures. Classes define functions called methods,
which identify the behaviors and actions that an object created from the class can perform with
its data. Create a Dog class that stores some information about the characteristics and behaviors
that an individual dog can have.

Page 118
PYTHON PROGRAMMING KG College of Arts and Science
A class is a blueprint f e g d be def ed. I d e ac a c a a
data. The Dog class specifies that a name and an age are necessary for defining a dog, but it
doe c a e a e age f a ec f c d g.
While the class is the blueprint, an instance is an object that is built from a class and contains
real data. An instance of the Dog c a ab e a e. I a ac a d g a a e,
like M e , f ea d.
Put another way, a class is like a form or questionnaire. An instance is like a form that has been
filled out with information. Just like many people can fill out the same form with their own
unique information, many instances can be created from a single class.
Instantiate an Object in Python
O e IDLE e ac e d a d e ef g:

>>> class Dog:


... pass

This creates a new Dog class with no attributes or methods. Creating a new object from a class is
called instantiating an object. can instantiate a new Dog object by typing the name of the class,
followed by opening and closing parentheses:

>>> Dog()
<__main__.Dog object at 0x106702d30>

now have a new Dog object at 0x106702d30. This funny-looking string of letters and numbers is
a memory address that indicates where the Dog b ec ed c e e .
Note that the address you see on your screen will be different.
Now instantiate a second Dog object:

>>> Dog()
<__main__.Dog object at 0x0004ccc90>

The new Dog a ce ca ed a a d ffe e e add e . T a beca e a e e


new instance and is completely unique from the first Dog object that you instantiated.
To see this another way, type the following:

>>> a = Dog()
>>> b = Dog()
>>> a == b
False

In this code, create two new Dog objects and assign them to the variables a and b. When you
compare a and b using the == operator, the result is False. Even though a and b are both
instances of the Dog class, they represent two distinct objects in memory.

The Dog c a e ee g g , e ce a b b def g e


properties that all Dog objects should have. There are a number of properties that we can choose

Page 119
PYTHON PROGRAMMING KG College of Arts and Science
from, including name, age, c a c , a d b eed. T ee g e, e e a ea d
age.
The properties that all Dog objects must have are defined in a method called .__init__().
Every time a new Dog object is created, .__init__() sets the initial state of the object by
a g g e a e f e b ec e e. T a , .__init__() initializes each new
instance of the class.
Can give .__init__() any number of parameters, but the first parameter will always be
a variable called self. When a new class instance is created, the instance is automatically passed
to the self parameter in .__init__() so that new attributes can be defined on the object.
Le da e e Dog class with an .__init__() method that creates .name and .age attributes:

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

Notice that the .__init__() e d g a e de ed f ace . T e b d f e


method is indented by eight spaces. This indentation is vitally important. It tells Python that
the .__init__() method belongs to the Dog class.
In the body of .__init__(), there are two statements using the self variable:
1. self.name = name creates an attribute called name and assigns to it the value of
the name parameter.
2. self.age = age creates an attribute called age and assigns to it the value of
the age parameter.
Attributes created in .__init__() are called instance attributes. A a ce a b e a e
is specific to a particular instance of the class. All Dog objects have a name and an age, but the
values for the name and age attributes will vary depending on the Dog instance.
On the other hand, class attributes are attributes that have the same value for all class instances.
You can define a class attribute by assigning a value to a variable name outside of .__init__().
For example, the following Dog class has a class attribute called species with the value "Canis
familiaris":

class Dog:
# Class attribute
species = "Canis familiaris"

def __init__(self, name, age):


self.name = name
self.age = age

Class attributes are defined directly beneath the first line of the class name and are indented by
four spaces. They must always be assigned an initial value. When an instance of the class is
created, class attributes are automatically created and assigned to their initial values.
Use class attributes to define properties that should have the same value for every class instance.
Use instance attributes for properties that vary from one instance to another.
Now in Dog c a , e c ea e ed g !

Class and Instance Attributes:


Now create a new Dog class with a class attribute called .species and two instance attributes
called .name and .age:
Page 120
PYTHON PROGRAMMING KG College of Arts and Science
>>> class Dog:
... species = "Canis familiaris"
... def __init__(self, name, age):
... self.name = name
... self.age = age

To instantiate objects of this Dog class, need to provide values for the name and age. If d ,
then Python raises a TypeError:
>>> Dog()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
Dog()
TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'

To pass arguments to the name and age parameters, put values into the parentheses after the class
name:
>>> buddy = Dog("Buddy", 9)
>>> miles = Dog("Miles", 4)

This creates two new Dog instances one for a nine-year-old dog named Buddy and one for a
four-year-old dog named Miles.
The Dog c a .__init__() method has three parameters, so why are only two arguments
passed to it in the example?
When instantiate a Dog object, Python creates a new instance and passes it to the first parameter
of .__init__(). This essentially removes the self-parameter, so need to worry about
the name and age parameters.
After create the Dog instances, can access their instance attributes using dot notation:
>>> buddy.name
'Buddy'
>>> buddy.age
9

>>> miles.name
'Miles'
>>> miles.age
4
can access class attributes the same way:
>>> buddy.species
'Canis familiaris'

One of the biggest advantages of using classes to organize data is that instances are guaranteed
to have the attributes you expect. All Dog instances have .species, .name, and .age attributes,
so can use those attributes with confidence knowing that they will always return a value.
Although the attributes are guaranteed to exist, their values can be changed dynamically:
>>> buddy.age = 10
>>> buddy.age
10

>>> miles.species = "Felis silvestris"


>>> miles.species
'Felis silvestris'

Page 121
PYTHON PROGRAMMING KG College of Arts and Science
In this example, change the .age attribute of the buddy object to 10. Then change
the .species attribute of the miles object to "Felis silvestris", which is a species of cat.
That makes Miles a pretty strange dog, but it is valid Python!
The key takeaway here is that custom objects are mutable by default. An object is mutable if it
can be altered dynamically. For example, lists and dictionaries are mutable, but strings and
tuples are immutable.

5.3 CLASS VARIABLES and INSTANCE VARIABLES:


Object-oriented programming allows for variables to be used at the class level or the instance
level. Variables a e e e a b a a d f a a e e g a ga .
At the class level, variables are referred to as class variables, whereas variables at the instance
level are called instance variables.
When it is expected that variables are going to be consistent across instances, or like to
initialize a variable, can define that variable at the class level. When anticipate the variables will
change significantly across instances, can define them at the instance level.

A class variable alone looks like the following:


class Shark:
animal_type = "fish"

Here, the variable animal_type is assigned the value "fish".


can create an instance of the Shark class (call it new_shark) and print the variable by using dot
notation

class Shark:
animal_type = "fish"

new_shark = Shark()
print(new_shark.animal_type)

Output
fish
program returns the value of the variable.
Add a few more class variables and print them out
#shark.py
class Shark:
animal_type = "fish"
location = "ocean"
followers = 5

new_shark = Shark()
print(new_shark.animal_type)
print(new_shark.location)
print(new_shark.followers)

Page 122
PYTHON PROGRAMMING KG College of Arts and Science
Just like with any other variable, class variables can consist of any data type available to us in
P .I ga a e g a da ege . Le e g a aga e python
shark.py command and review the output:
Output
fish
ocean
5

The instance of new_shark is able to access all the class variables and print them out when run
the program.
Class variables allow us to define variables upon constructing the class. These variables and their
associated values are then accessible to each instance of the class.
5.3.1 INSTANCE VARIABLES
Instance variables are owned by instances of the class. This means that for each object or
instance of a class, the instance variables are different. Unlike class variables, instance variables
are defined within methods.
In the Shark class example below, name and age are instance variables:
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age

When create a Shark object, we will have to define these variables, which are passed as
parameters within the constructor method or another method.
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age

new_shark = Shark("Sammy", 5)

As with class variables, can similarly call to print instance variables:


#shark.py
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age

new_shark = Shark("Sammy", 5)
print(new_shark.name)
print(new_shark.age)

When run the program above with python shark.py, receive the following output:
Output
Sammy
5

The output received is made up of the values of the variables that we initialized for the object
instance of new_shark.
Le c ea e a e b ec f e Shark class called stevie:
#shark.py
class Shark:
def __init__(self, name, age):
Page 123
PYTHON PROGRAMMING KG College of Arts and Science
self.name = name
self.age = age

new_shark = Shark("Sammy", 5)
print(new_shark.name)
print(new_shark.age)

stevie = Shark("Stevie", 8)
print(stevie.name)
print(stevie.age)

Output
Sammy
5
Stevie
8

The stevie object, like the new_shark object passes the parameters specific for that instance of the Shark
class to assign values to the instance variables.
Instance variables, owned by objects of the class, allow for each object or instance to have different
values assigned to those variables.

5.3.2 Working with Class and Instance Variables together :


Ca a ab e a d a ce a ab e f e be ed a e a e e, e a a
example of this using the Shark class we created. The comments in the program outline each
step of the process.
#shark.py
class Shark:

# Class variables
animal_type = "fish"
location = "ocean"

# Constructor method with instance variables name and age


def __init__(self, name, age):
self.name = name
self.age = age

# Method with instance variable followers


def set_followers(self, followers):
print("This user has " + str(followers) + " followers")

def main():
# First object, set up instance variables of constructor method
sammy = Shark("Sammy", 5)

# Print out instance variable name


print(sammy.name)

# Print out class variable location


Page 124
PYTHON PROGRAMMING KG College of Arts and Science
print(sammy.location)

# Second object
stevie = Shark("Stevie", 8)

# Print out instance variable name


print(stevie.name)

# Use set_followers method and pass followers instance variable


stevie.set_followers(77)

# Print out class variable animal_type


print(stevie.animal_type)

if __name__ == "__main__":
main()

When run the program with python shark.py, receive the following output:
Output
Sammy
ocean
Stevie
This user has 77 followers
fish
Here, it is made use of both class and instance variables in two objects of
the Shark class, sammy and stevie.

5.4 INSTANCE METHODS :


Instance methods are functions that are defined inside a class and can only be called from an
instance of that class. Just like .__init__(), a a ce e d f aa ee
always self.
Open a new editor window in IDLE and type in the following Dog class:
class Dog:
species = "Canis familiaris"

def __init__(self, name, age):


self.name = name
self.age = age

# Instance method
def description(self):
return f"{self.name} is {self.age} years old"

# Another instance method


def speak(self, sound):
return f"{self.name} says {sound}"

This Dog class has two instance methods:


1. .description() returns a string displaying the name and age of the dog.
2. .speak() has one parameter called sound and returns a s g c a g ed g
name and the sound the dog makes.

Page 125
PYTHON PROGRAMMING KG College of Arts and Science
Save the modified Dog class to a file called dog.py and press F5 to run the program. Then open
the interactive window and type the following to see your instance methods in action:
>>>
>>> miles = Dog("Miles", 4)

>>> miles.description()
'Miles is 4 years old'

>>> miles.speak("Woof Woof")


'Miles says Woof Woof'

>>> miles.speak("Bow Wow")


'Miles says Bow Wow'

In the above Dog class, .description() returns a string containing information about
the Dog instance miles. When writing e ca e , a g d dea a ea e d a
returns a string containing useful information about an instance of the class.
However, .description() e Pythonic way of doing this.
When a list object is created , can use print() to display a string that looks like the list:
>>>
>>> names = ["Fletcher", "David", "Dan"]
>>> print(names)
['Fletcher', 'David', 'Dan']
Le see what happens when you print() the miles object:
>>>
>>> print(miles)
<__main__.Dog object at 0x00aeff70>

On use of print(miles),get a cryptic looking message telling that miles is a Dog object at the
memory address 0x00aeff70. T e age e helpful. Can change what gets printed by
defining a special instance method called .__str__().
In the editor window, change the name of the Dog c a .description() method
to .__str__():
class Dog:
# Leave other parts of Dog class as-is
# Replace .description() with __str__()
def __str__(self):
return f"{self.name} is {self.age} years old"
Save the file and press F5 . Now, when you print(miles), you get a much friendlier output:

>>> miles = Dog("Miles", 4)


>>> print(miles)
'Miles is 4 years old'
Methods like .__init__() and .__str__() are called dunder methods because they begin and
end with double underscores. There are many dunder methods that you can use to customize
classes in Python. Although too advanced a topic for a beginning Python book, understanding
dunder methods is an important part of mastering object-oriented programming in Python.

5.5 CREATE CLASSES FROM OTHER CLASSES :


5.5.1 Inherit From Other Classes in Python

Page 126
PYTHON PROGRAMMING KG College of Arts and Science
Inheritance is the process by which one class takes on the attributes and methods of another.
Newly formed classes are called child classes, and the classes that child classes are derived from
are called parent classes.
Child classes can override or extend the attributes and methods of parent classes. In other words,
c dca e e a f e ae a b e a d e d b ca a ec f a b e a d
methods that are unique to themselves.
Parent Classes vs Child Classes :
Le c ea e a c d c a f eac f e ee b eed e ed ab e: Jack Russell Terrier,
Dac d, a d B d g. F efe e ce, e e e f def f e Dog class:

class Dog:
species = "Canis familiaris"

def __init__(self, name, age):


self.name = name
self.age = age

def __str__(self):
return f"{self.name} is {self.age} years old"

def speak(self, sound):


return f"{self.name} says {sound}"

Remember, to create a child class, you create new class with its own name and then put the name
of the parent class in parentheses. Add the following to the dog.py file to create three new child
classes of the Dog class:
class JackRussellTerrier(Dog):
pass

class Dachshund(Dog):
pass

class Bulldog(Dog):
pass

Press F5 to save and run the file. With the child classes defined, can now instantiate some dogs
of specific breeds in the interactive window:
>>>
>>> miles = JackRussellTerrier("Miles", 4)
>>> buddy = Dachshund("Buddy", 9)
>>> jack = Bulldog("Jack", 3)
>>> jim = Bulldog("Jim", 5)
Instances of child classes inherit all of the attributes and methods of the parent class:
>>>
>>> miles.species
'Canis familiaris'

>>> buddy.name
'Buddy'

Page 127
PYTHON PROGRAMMING KG College of Arts and Science
>>> print(jack)
Jack is 3 years old

>>> jim.speak("Woof")
'Jim says Woof'
To determine which class a given object belongs to, you can use the built-in type():
>>>
>>> type(miles)
<class '__main__.JackRussellTerrier'>
What if you want to determine if miles is also an instance of the Dog class? You can do this with
the built-in isinstance():
>>>
>>> isinstance(miles, Dog)
True

Notice that isinstance() takes two arguments, an object and a class. In the example
above, isinstance() checks if miles is an instance of the Dog class and returns True.
The miles, buddy, jack, and jim objects are all Dog instances, but miles is not
a Bulldog instance, and jack is not a Dachshund instance:
>>>
>>> isinstance(miles, Bulldog)
False

>>> isinstance(jack, Dachshund)


False

More generally, all objects created from a child class are instances of the parent class, although
they may not be instances of other child classes.
N a c ea ed c d c a e f e d ffe e b eed f d g , e g e eac b eed
sound.
5.6 INHERITANCE :
Inheritance is the capability of one class to derive or inherit the properties from another class.
The class that derives properties is called the derived class or base class and the class from
which the properties are being derived is called the base class or parent class. The benefits of
inheritance are:
It represents real-world relationships well.
It provides the reusab f a c de. We d a e e e a e c de aga a d aga .
Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.
Example: Inheritance in Python
# Python code to demonstrate how parent constructors are called parent class
class Person(object):
# __init__ is known as the constructor
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))

Page 128
PYTHON PROGRAMMING KG College of Arts and Science
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")
# calling a function of the class Person using its instance
a.display()
a.details()
Output
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern

5.6.1 WHAT IS AN INHERITANCE IN PYTHON?

Just like a parent-child relationship, inheritance works on derived classes relative to the base
ca .E e De ed c a e f a Ba e c a . T e e a ce e e e ed UML
or Unified Modeling Language. It is a standard modeling language that includes an integrated set
of diagrams to help developers specify, structure, and document software systems elements.
Inheritance relationship defines the classes that inherit from other classes as derived, subclass, or
sub-type classes. Base class remains to be the source from which a subclass inherits. For
e a e, a e a Ba e c a f A a, a da L a De ed c a . T e e a ce
will be Lion is an Animal.
So, the question is, what does the “Lion” class inherit from “Animal”?
A L ca e

Page 129
PYTHON PROGRAMMING KG College of Arts and Science
Interface
Execution
Advantages of Inheritance in Python
Inheritance in Python helps developers to reuse the objects.
Eac eaca e e ba e c a , ge acce e ae b ec
functionality.
Reusability due to inheritance is also reliable as the base class is already
tested.
Low development time and cost
Standardization of the interface across classes becomes easy.
Reduces redundancy of code and help improve extensibility
The creation of class libraries becomes easy.

5.6.2 TYPES OF INHERITANCE IN PYTHON :

1. SINGLE INHERITANCE
Single inheritance is- e e a ce f e De ed c a f e Ba e c a . Le
understand it through an example,
class Country:
def ShowCountry(self):
( T S a );
class State(Country):
def ShowState(self):
( T S a e );
st =State();
st.ShowCountry();
st.ShowState();

2.MULTI-LEVEL INHERITANCE

Page 130
PYTHON PROGRAMMING KG College of Arts and Science

Python is made of several objects, and with the multi-level inheritance, there are endless
possibilities of reusing the class functionalities. Multi-level inheritance gets documented each
time a derived class inherits another derived class. There is no limit to the number of derived
classes that can inherit the functionalities, and that is why multilevel inheritance helps to
improve the reusability in Python.

# Example of multilevel inheritance


class Animal:
def speak(self):
( A a S ea g )
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
( d g ba g )
#The child class Dogchild inherits another child class
Dog
class DogChild(Dog):
def eat(self):
( Ea g b ead )
d = DogChild()
d.bark()
d.speak()
d.eat()

Page 131
PYTHON PROGRAMMING KG College of Arts and Science
3. MULTIPLE INHERITANCE:

Python enables developers to inherit multiple functionalities and properties from different base
classes into a single derived class. It is mostly a great feature as it can allow you to inherit
multiple dependencies without extensive tools or coding.

#Example for multiple inheritances.


class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

4.HIERARCHICAL INHERITANCE
Hierarchical inheritance involves multiple inheritance from the same base or parent class.
Page 132
PYTHON PROGRAMMING KG College of Arts and Science

#Example for hierarchical Inheritance


class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")

ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()

5.HYBRID INHERITANCE
Hybrid inheritance involves multiple inheritance taking place in a single program.
class Parent:
def func1(self):
print("this is function one")

class Child(Parent):
def func2(self):
print("this is function 2")

class Child1(Parent):
def func3(self):
print(" this is function 3"):

class Child3(Parent , Child1):


def func4(self):
print(" this is function 4")

ob = Child3()
ob.func1()

Page 133
PYTHON PROGRAMMING KG College of Arts and Science

How to identify a Derived Class?


Python comes with a built-in issubclass() function that helps developers check whether a class is
a de ed e a ba e c a . O ce f c , e a e T e f
subclass or a Derived class, while False for Base class.

A developer can check the class through this example.


class myAge:
age = 36
class myObj(myAge):
a e= J
age = myAge
x = issubclass(myObj, myAge)

How to create a class hierarchy in Python?


Inheritance in Python helps create hierarchies of classes. All the relative classes will share a
common interface to communicate with each other. A Base class defines the interface. Derived
classes can provide specific specialization of the interface. Here, exploring an HR model to
demonstrate the class hierarchy.
The HR system will process payroll for different company workers; each worker is identified
through an ID and has different payroll positions to be calculated.
Le f c ea e a a c a a e Ba e b ec .
# In hr.py
class PayrollSystem:
def calculate_payroll(self, workers):
( Ca c a g Pa )
( =================== )
for worker in workers:
(f Pa f : e.d e. a e )
(f - C ec a : e .ca c a e_ a () )
p ( )

The PayrollSystem executes a .ca c a e_ a () e d a c ec e e f a ,


prints their id, name, and checks the payroll amount. Now, you run a base class worker that
tackles the standard interface for every worker type:
# In hr.py
class Worker:
def __init__(self, id, name):
self.id = id
self.name = name

Creating a Worker base class for all the worker types in the company makes the hierarchy easy
for the HR system. Every worker is assigned a name and id. The HR system requires the worker
to provide data regarding their weekly salary through the .calculate_payroll() interface. The
execution of this interface may differ according to the type of worker.

Why is inheritance significant in Python?


Inheritance refers to the process of passing on the properties of a parent class to a child class. It
is an object-oriented programming(OOP) concept and is significant in Python. It is because
inheritance provides code reusability, which means that instead of writing the same code over
Page 134
PYTHON PROGRAMMING KG College of Arts and Science
and again, we can inherit the attributes we require in a child class. It is also easy to understand
and implement since it depicts a real-world relationship between the parent and child classes. It
has a transitive nature. Because all child classes inherit properties from their parents, any
subclasses will likewise use the parent class's functionalities.

Is inheritance necessary while learning Python?


Yes, learning inheritance is necessary while learning Python. Massive python applications
necessitate a rise in the number of python programmers in the current market. This surge has led
to an increase in the number of people learning Python. The Python programming language is
rich in notions such as inheritance. One of the essential concepts in this Object-oriented
programming language is inheritance. As inheritance allows for code reusability, readability, and
properties transition, learning it while learning Python is imperative. Inheritance aids in creating
accurate and efficient code.

In Python, which types of inheritance are not supported?


Python allows all forms of inheritance, including multiple inheritances, unlike other object-
oriented programming languages. It is possible to construct new classes from pre-existing ones
using the inheritance concept. This facilitates the reuse of code. The methods specified in the
parent class are also used in the child class. While C++ also enables this sort of inheritance, it
lacks Python's advanced and well-designed methodology. Python even offers Hybrid inheritance,
which allows us to implement many types of inheritance in a single piece of code. Because code
reusability is a strength of inheritance, it is helpful in a wide range of applications when working
with Python.

The benefits of inheritance are:

1. It represents real-world relationships well.


2. It provides reusability f a c de. We d a e e e a e c de aga a d aga .
Also, it allows us to add more features to a class without modifying it.
3. It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.

5.7 POLYMORPHISM IN PYTHON:


Suppose there is a class called animal, but in that class, a whole lot of forms are there like
dog, cat, cow etc. That means a common class animal consists of different forms that exist in
various forms and shapes and have different functionalities. This whole thing can be defined
by a single term called polymorphism. Polymorphism in python is something that is used to
describe the ability to take various forms. The word is derived from two different words
poly which means many and morphs meaning forms. The literal meaning of polymorphism is
the condition of occurrence in different forms. Polymorphism is a very important concept in
programming. It refers to the use of a single type entity (method, operator or object) to represent
different types in different scenarios.

i)Constructor :
Constructor is a type of subroutine in object-oriented programming. Constructor is used to
assigning value to data members when an object is created inside a class. The __init__()
function is used as a constructor in python almost every time create an object. In
polymorphism, this __init__() function is used almost everywhere.

Page 135
PYTHON PROGRAMMING KG College of Arts and Science
What is polymorphism in Python?
Polymorphism in Python is used for a common function name that can be used for different
types. This concept is widely applied in object-oriented based Python programming. Like
other programming languages say Java, C+, polymorphism is also implemented in python for
different purpose commonly Duck Typing, Operator overloading and Method overloading,
and Method overriding. This polymorphism process can be achieved in two main ways
namely overloading and overriding.

#A simple example of polymorphism in python


#Example 1
>>>4+5
9

#Example 2
>>> 4 + 5
45

#Example 3
>>> ab + cd
abcd

In the above example can clearly see that the addition operator is used in different way.
In the first example the as the data sent are two integer values, the operator did the addition
operation of two numbers.
And in the second example, as the same values are sent as data in the form of string, and the
same operator did the concatenation (concatenation is the process by which two strings ar e
joined end-to-end) of the two strings.
In the third example, the data sent are two strings but the operator is same as the above and
it did the concatenation of the two strings.

>>> 3 + ab
3ab

In this example the addition operator did the concatenation of the two strings though the first
value is a integer but here in this specific example it is sent as strings.
So these were the few basic examples of polymorphism in python.

5.7.1 How to use polymorphism?


A)Overloading
Overloading is divided into two types
i)Operator Overloading
ii)Method Overloading
i)Operator overloading
Operator overloading is the type of overloading in which an operator can be used in multiple
ways beyond its predefined meaning.

>>>print(2*7)
14

>>> ( a *3)
aaa

Page 136
PYTHON PROGRAMMING KG College of Arts and Science
So in the above example the multiplication operator did the multiplication of two numbers in
the first one, but in the second one as the multiplication of a string and an integer is not
possible so the character is printed repeatedly for 3 times. So it shows how a single operator
can be used in different way.

Application of operator overloading is done by overloading the special function


__add__ operator.

class Vehicle:
def __init__(self, fare):
self.fare = fare
def __add__(self, other)://using the special function __add__ operator
return self.fare+ other.fare

bus= Vehicle(20)
car= Vehicle(30)
total_fare=bus+ car
print(total_fare)

#Output:
50

Overloading the special function magically defines everytime plus operator is used in the
object total_fare=bus+ car . User is going to add their fares
#Example 2: Let us compare the fares of different vehicles in this example
class Vehicle:
def __init__(self, fare):
self.fare = fare
def __lt__(self, other):// relational operator __lt__ is used here as the special function
return self.fare< other.fare

bus= Vehicle(10)
car= Vehicle(30)
compare=bus< car
print(compare)

Output:
True

__lt__ It is the relational operator which is used as a special function for operator
overloading in the above example.

ii)Method Overloading
Method overloading means a class containing multiple methods with the same name but
may have different arguments. Basically python does not support method overloading, but
there are several ways to achieve method overloading. Though method overloading can be
achieved, the last defined methods can only be usable.
Le ake an e am le fo be e nde anding
Le c de a c a A, eca a e a e af c c a ac c or
self and arguments whose default values assigned are None and None. User created an object
a d ca ed e f c e b ec b . ,b dd a a ag e g
print None and None cause in the function part assigned the default values.
Example:
Page 137
PYTHON PROGRAMMING KG College of Arts and Science
class A:
def show(self, a=None, b=None):
print(a,b)

obj=A()
obj.show()
Output
None None
Now to pass any other value then that need to call another function obj.show() with an
argument in it.
Example:
class A:
def show(self, a=None, b=None):
print(a,b)

obj=A()
obj.show()
obj.show(4)
Output
None None
4 None
Here in the output the None value assigned for a in the function part is replaced with 4. In
the function call part 4 is passed as the argument.
Now two argument is passed during the function call see what will happen in the next
example,
#Example:
class A:
def show(self, a=None, b=None):
print(a,b)

obj=A()
obj.show()
obj.show(4)
obj.show(4,5)
Output
None None
4
45

Here as two arguments 4 and 5 are passed during function call two different values are
assigned for a and b.So in the above example the same method and use different f unction
calls in different ways is seen

B)METHOD OVERRIDING :
Method overriding is the process of modifying a base class from the derived class having the
same methods and same number of arguments. Le a e a e a e a d ee
works. First of all create a base class with a method and then create a derived class without
any method,
#Example:
class Vehicle:
def run(self):
print("Saves Energy")
class EV(Vehicle):
pass

ev = EV()
Page 138
PYTHON PROGRAMMING KG College of Arts and Science
ev.run()

S e ef c ca ed, e e ba e c a e d, a e de ed
class has no method in it.

Output:
Saves Energy

Now in the next example declare another method under the derived class with the same
a e a ba e c a b a d ffe e a g e . A e ba e c a e d
e dde b e de ed c a , e de ed c a e d be ed a e .
#Example:
class Vehicle:
def run(self):
print("Saves Energy")

class EV(Vehicle):
def run(self):
print("Run on Electricity")

ev = EV()
ev.run()

Output
Run on Electricity

Duck Typing
Duck typing is a concept in polymorphism. The term duck typing is derived from the quote
which says something that walks like a duck quacks like a duck and swims like a duck is
called a duck no matter what object it is. In simple words it means something that matches
its behaviour to anything then it will consider a thing of that category to which it matches.

Why is polymorphism needed?

When Talking about object-oriented programming in python the term polymorphism will
come for sure. In object-oriented programming, objects need to take different forms. In
s f a e de e e , e a a e fea e. T g , a
single action can be performed in various ways. This concept is widely used when we talk
about loose coupling, dependency injection and interface etc.

OTHER EXAMPLES OF POLYMORPHISM :


Example 1: Polymorphism in addition operator
Know that the + operator is used extensively in Python programs. But, it does not have a single
usage.
For integer data types, + operator is used to perform arithmetic addition operation.
#example
num1 = 1
num2 = 2
print(num1+num2)
Hence, the above program outputs 3.

Page 139
PYTHON PROGRAMMING KG College of Arts and Science
Similarly, for string data types, + operator is used to perform concatenation.

str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)
As a result, the above program outputs Python Programming.
Here, a single operator + has been used to carry out different operations for distinct data types.
This is one of the most simple occurrences of polymorphism in Python.

Function Polymorphism in Python


There are some functions in Python which are compatible to run with multiple data types.
One such function is the len() function. It can run with many data types in Python. Let's look at
some example use cases of the function.
Example 2: Polymorphic len() function
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))

Output
9
3
2
Here, many data types such as string, list, tuple, set, and dictionary can work with
the len() function. However, can see that it returns specific information about specific data
types.

Polymorphism in len() function in Python

Class Polymorphism in Python


Polymorphism is a very important concept in Object-Oriented Programming. Use the concept of
polymorphism while creating class methods as Python allows different classes to have methods
with the same name. Can then later generalize calling these methods by disregarding the object
working with. Let's look at an example:
Example 3: Polymorphism in Class Methods

Page 140
PYTHON PROGRAMMING KG College of Arts and Science
Here, we have created two classes Cat and Dog . They share a similar structure and have the
same method names info() and make_sound() .
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Meow")

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Bark")

cat1 = Cat("Kitty", 2.5)


dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):


animal.make_sound()
animal.info()
animal.make_sound()
Output
Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark

However, notice that it have not created a common superclass or linked the classes together in
any way. Even then, can pack these two different objects into a tuple and iterate through it using
a common animal variable. It is possible due to polymorphism.

5.8 SUPER() FUNCTION :


N a f e ba e c a e d a bee e dde , e e d f e ba e c a
cannot be called normally. So to call the method of base class have to use the super function
in the overridden method under the derived class.
Example:
class Vehicle:
def run(self):
print("Saves Energy")

Page 141
PYTHON PROGRAMMING KG College of Arts and Science
class EV(Vehicle):
def run(self):
super().run()//super function is used to call the method of base class

print("Run on Electricity")

ev = EV()
ev.run()

Output:
Saves Energy
Run on Electricity

5.9 POLYMORPHISM AND INHERITANCE :


Like in other programming languages, the child classes in Python also inherit methods and
attributes from the parent class. Certain methods and attributes can be redesigned specifically to
fit the child class, which is known as Method Overriding. Polymorphism allows us to access
these overridden methods and attributes that have the same name as the parent class.
Let's look at an example:
Example 4: Method Overriding

from math import pi


class Shape:
def __init__(self, name):
self.name = name

def area(self):
pass

def fact(self):
return "I am a two-dimensional shape."

def __str__(self):
return self.name

class Square(Shape):
def __init__(self, length):
super().__init__("Square")
self.length = length

def area(self):
return self.length**2

def fact(self):
return "Squares have each angle equal to 90 degrees."

class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius

Page 142
PYTHON PROGRAMMING KG College of Arts and Science
def area(self):
return pi*self.radius**2

a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
Output
Circle
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985

Here, can see that the methods such as __str__() , which have not been overridden in the child
classes, are used from the parent class.
Due to polymorphism, the Python interpreter automatically recognizes that the fact() method
for object a (Square class) is overridden. So, it uses the one defined in the child class.
On the other hand, since the fact() method for object b isn't overridden, it is used from the
Parent Shape class.

Polymorphism in parent and child classes in Python


Note: Method Overloading, a way to create multiple methods with the same name but different
arguments, is not possible in Python.

Overview of OOP Terminology :


Class A e -defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables and
instance variables) and methods, accessed via dot notation.
Class variable A a able that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not
used as frequently as instance variables are.
Data member A c a a ab e a ce a ab e a holds data associated with a
class and its objects.

Page 143
PYTHON PROGRAMMING KG College of Arts and Science
Function overloading T e a g e f e a e be a a a c a
function. The operation performed varies by the types of objects or arguments involved.
Instance variable A a ab e a is defined inside a method and belongs only to the
current instance of a class.
Inheritance T e a fe f e c a ac e c f a ca e ca e a ae
derived from it.
Instance A d d a b ec f a ce a c a . A b ec b a belongs to a class
Circle, for example, is an instance of the class Circle.
Instantiation T e c ea fa a ce f a c a .
Method A ec a d ff c a def ed a c a def .
Object A e a ce f a da a c e at's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Operator overloading T e a g e f e a e f c a a c a
operator.

5.10 SPECIAL METHODS:

Everything in Python is an object and define objects through classes. To define an object,
actually create an instance of a class. Thus, class is the most fundamental piece in Python.
P special methods (called magic methods).
The names of these methods begin and end with double underscores (__).
Suppose t have a simple Word class, and want an equals() method that compares two
words but ignores case.
That is, a Word containing the value 'kg' would be considered equal to one containing 'KG'.

Classes have:
Data attributes: Define what is needed to create an instance of a class
Methods (i.e. procedural attributes): Define how to interact with the instances of a class

Own classes using data and procedural attributes can be created and can implement various
functions to customize a class. In addition to the user-defined functions, it is possible to use built-
in Python function within user-defined classes. This is what special (or magic) methods are for.

Special methods allow for using the built-in Python functions to enrich user-defined classes.
Consider the print function which is one of the most commonly used Python function. To print an
instance of the class, it will print out something like the following:
<__main__.Book object at 0x7f9ed5b1d590>
It displays the name of the class (Book) and the memory location of the object which is not a
proper use of the print function. Can customize its behavior by implementing the __str__ special
method in our class.
#Example
>>> class Word():
def __init__(self, text):
self.text = text
def __eq__(self, word2):
return self.text.lower() == word2.text.lower()
Le ee f :
>>> first = Word('kg')
Page 144
PYTHON PROGRAMMING KG College of Arts and Science
>>> ec d = W d('KG )
>>> third = Word('eh')
>>> first == second
True
>>> first == third

4 special methods that will be likely to use in the classes.

1. __init__

The __init__ special method is automatically executed when an instance of class is created. It is
also called class constructor. The parameters of the __init__ represent the data attributes of a
class.
Le c ea e a c a ca ed B .

class Book(): def __init__(self, name, writer, pages):

self.name = name

self.writer = writer

self.pages = pages

The self refers to the instance itself. The Book class has 3 data attributes that need to be specified
when creating a Book instance.

b = Book("Moby Dick", "Herman Melville", "378")type(b)


__main__.Book

The variable b is an instance of the Book class.

2. __str__

use the __str__ special method to implement the built-in print function within our class. Without
the __str__, here is what print function does.
print(b)
<__main__.Book object at 0x7f9ed5b1d590>
Le def e e __ __ e d c a def .
def __str__(self):

return f"The title of the book is {self.name}"

Now the print function will return the title of the name. It accesses the name of the book through
the name attribute. can customize it in any way

print(b)
The title of the book is Moby Dick

3. __len__

Page 145
PYTHON PROGRAMMING KG College of Arts and Science
The len function returns the length of an object. For strings, it returns the number of characters.
For a Pandas data frame, it returns the number of row. Can customize its behavior by
e e g e __ e __ ec a e d c a def . Le a e e e
number of pages of a book object.
If the __len__ is not implemented in the class definition, you will get an error if you try to use
it on an object of your class. It does not have a default behavior like the print function.

def __len__(self):

return int(self.pages)

len(b)
378
Please note that each time a new function is added to the class, need to recreate the object to be
able to use the new functions.

4. __eq__

The __eq__ special method allows for comparing two instances of a class. If it is defined in the
class, can check if an instance is equal to another instance. The equality condition is specified
using the __eq__ method.
In this case, can declare two books being equal if the names and writers of the book are the
same. They might have different number of pages.

def __eq__(self, other):


return (self.name == other.name) & (self.writer == other.writer)

T e == ea e T e fb a e a d e ae e a ef a ce . Le
create two books and check if they are equal.

b = Book("Moby Dick", "Herman Melville", "378")


a = Book("Moby Dick", "Herman Melville", "410")
b == a
True
If either names or writes is different, the equality operator returns False.

b = Book("Moby Dick", "Herman Melville", "378")a = Book("Moby Dick", "Melville", "410")


b == a
False

5.10.1 OTHER SPECIAL METHODS :

Table SP. lists special methods that objects must implement to emulate numbers. Mathematical
operations are always evaluated from left to right; when an expression such as x + y appears,
the interpreter tries to invoke the method x.__add__(y). The special methods beginning with r
ea e e ed e a d . T e e a e ed f e ef ea dd e
implement the specified operation. For example, if x in x + y doe
the __add__() method, the interpreter tries to invoke the method y.__radd__(x).

Table SP: Methods for Mathematical Operations


Method Result
__add__(self,other) self + other
Page 146
PYTHON PROGRAMMING KG College of Arts and Science
__sub__(self,other) self – other
__mul__(self,other) self * other
__div__(self,other) self / other
__truediv__(self,other) self / other (future)
__floordiv__(self,other) self // other
__mod__(self,other) self % other
__divmod__(self,other) divmod(self,other)
__pow__(self,other [,modulo]) self ** other, pow(self, other, modulo)
__lshift__(self,other) self << other
__rshift__(self,other) self >> other
__and__(self,other) self & other
__or__(self,other) self | other
__xor__(self,other) self ^ other
__radd__(self,other) other + self
__rsub__(self,other) other - self
__rmul__(self,other) other * self
__rdiv__(self,other) other / self
__rtruediv__(self,other) other / self (future)
__rfloordiv__(self,other) other // self
__rmod__(self,other) other % self
__rdivmod__(self,other) divmod(other,self)
__rpow__(self,other) other ** self
__rlshift__(self,other) other << self
__rrshift__(self,other) other >> self
__rand__(self,other) other & self
__ror__(self,other) other | self
__rxor__(self,other) other ^ self
__iadd__(self,other) self += other
__isub__(self,other) self -= other
__imul__(self,other) self *= other
__idiv__(self,other) self /= other
__itruediv__(self,other) self /= other (future)
__ifloordiv__(self,other) self //= other
__imod__(self,other) self %= other
__ipow__(self,other) self **= other
__iand__(self,other) self &= other
Method Result
__ior__(self,other) self |= other
__ixor__(self,other) self ^= other
__ilshift__(self,other) self <<= other
__irshift__(self,other) self >>= other
__neg__(self) self
__pos__(self) +self
__abs__(self) abs(self)
__invert__(self) ~self
__int__(self) int(self)
__long__(self) long(self)
__float__(self) float(self)
__complex__(self) complex(self)
Page 147
PYTHON PROGRAMMING KG College of Arts and Science
__oct__(self) oct(self)
__hex__(self) hex(self)
__coerce__(self,other) Type coercion

The methods __iadd__(), __isub__(), and so forth are used to support in-place arithmetic
operators such as a+=b and a-=b (also known as augmented assignment). A distinction is made
between these operators and the standard arithmetic methods because the implementation of the
in-place operators might be able to provide certain customizations such as performance
optimizations. For instance, if the self parameter is not shared, it might be possible to modify its
value in place without having to allocate a newly created object for the result.

The three flavors of division operators, __div__(), __truediv__(),


and __floordiv__(), are used to implement true division (/) and truncating division (//)
operations. The separation of division into two types of operators is a relatively recent change to
Python that was started in Python 2.2, but which has far-reaching effects. As of this writing, the
default behavior of Python is to map the / operator to __div__(). In the future, it will be
remapped to __truediv__(). This latter behavior can currently be enabled as an optional
feature by including the statement from __future__ import division in a program.
The conversion methods __int__(), __long__(), __float__(),
and __complex__() convert an object into one of the four built-in numerical types.
The __oct__() and __hex__() methods return strings representing the octal and hexadecimal
values of an object, respectively.
Comparison Operations
Table lists special methods that objects can implement to provide individualized versions of the
relational operators (<, >, <=, >=, ==, !=). These are known as rich comparisons. Each of these
functions takes two arguments and is allowed to return any kind of object, including a Boolean
value, a list, or any other Python type. For instance, a numerical package might use this to
perform an element-wise comparison of two matrices, returning a matrix with the results. If a
c a ca be ade, e e f c a a a e a e ce .

Table: Methods for Comparisons


Method Result
__lt__(self,other) self < other
__le__(self,other) self <= other
__gt__(self,other) self > other
__ge__(self,other) self >= other
__eq__(self,other) self == other
__ne__(self,other) self != other

By using the above special methods or magic methods or dunder methods can be utilised
efficiently for classes or for programming.

5.11 type() FUNCTION:


Python type() returns the type of the specified object if a single argument is passed to the type().
If three arguments are passed, it returns a new type of object. The type() function either returns
the type of the object or returns a new type object based on the arguments passed.
Signature :
type(object,bases,dict)

Page 148
PYTHON PROGRAMMING KG College of Arts and Science
Parameters
object: The type() returns the type of this object if one parameter is specified.
bases (optional): It specifies the base classes.
dict (optional): It specifies the namespace with the definition for the class.
Return
It returns the type of the specified object if a single argument is passed to the type(). If three
arguments are passed, it returns a new type of object.

#Python type() Function Example 1


#The below example shows how to get the type of an object.
List = [4, 5]
print(type(List))

Dict = {4: 'four', 5: 'five'}


print(type(Dict))

class Python:
a=0

InstanceOfPython = Python()
print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
Explanation: In the above example, we have taken a List that contains some values, and in
return, it prints the type of the List.
In the second case, we have taken a Dict that contains some values, and in return, it prints the
type of the Dict.
Then, defined a class named as Python and produced an InstanceOfPython which prints its type.

# Python3 simple code to explain the type() function


print(type([]) is list)
print(type([]) is not list)
print(type(()) is tuple)
print(type({}) is dict)
print(type({}) is not list)
The type() function either returns the type of the object or returns a new type object based on
the arguments passed.
#Example
prime_numbers = [2, 3, 5, 7]

# check type of prime_numbers


result = type(prime_numbers)

print(result)

# Output: <class 'list'>

type() Syntax
The type() function has two different forms:
# type with single parameter
Page 149
PYTHON PROGRAMMING KG College of Arts and Science
type(object)
# type with 3 parameters
type(name, bases, dict)

type() Parameters
The type() function either takes a single object parameter.
Or, it takes 3 parameters
name - a class name; becomes the __name__ attribute
bases - a tuple that itemizes the base class; becomes the __bases__ attribute
dict - a dictionary which is the namespace containing definitions for the class body;
becomes the __dict__ attribute
type() Return Value
The type() function returns type of the object, if only one object parameter is passed a new
type, if 3 parameters passed
Example 1: type() with Object parameter
numbers_list = [1, 2]
print(type(numbers_list))

numbers_dict = {1: 'one', 2: 'two'}


print(type(numbers_dict))
class Foo:
a=0
foo = Foo()
print(type(foo))
Output
<class 'list'>
<class 'dict'>
<class '__main__.Foo'>
To check the type of an object, it is better to use the Python isinstance() function instead. It's
because the isinstance() function also checks if the given object is an instance of the subclass.

#Example 2: type() With 3 Parameters


o1 = type('X', (object,), dict(a='Foo', b=12))
print(type(o1))
print(vars(o1))

class test:
a = 'Foo'
b = 12

o2 = type('Y', (test,), dict(a='Foo', b=12))


print(type(o2))
print(vars(o2))
Output :
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>,
'__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__doc__': None}

Page 150
PYTHON PROGRAMMING KG College of Arts and Science
In the program, have used the Python vars() function which returns
the __dict__ attribute. __dict__ is used to store object's writable attributes. can easily change
these attributes if necessary. For example, to change the __name__ attribute of o1 to 'Z' , use:

o1.__name = 'Z'

ANOTHER EXAMPLE :
# Python3 code to explain the type() function Class of type dict
class DictType:
DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'}

# Class of type list


class ListType:
ListNumber = [1, 2, 3, 4, 5]

# Creating object of each class


d = DictType()
l = ListType()

# Will print accordingly whether both the objects are of same type or not
if type(d) is not type(l):
print("Both class have different object type.")
else:
print("Same Object type")

5.12. REGULAR EXPRESSIONS :


What is Regular Expression in Python?
A Regular Expression (RE) in a programming language is a special text string used for
describing a search pattern. It is extremely useful for extracting information from text such as
code, files, log, spreadsheets or even documents.
While using the Python regular expression the first thing is to recognize is that everything is
essentially a character, and are writing patterns to match a specific sequence of characters also
referred as string. ASCII or latin letters are those that are on your keyboards and Unicode is used
to match the foreign text. It includes digits and punctuation and all special characters like
$#@!%, etc.
For instance, a Python regular expression could tell a program to search for specific text from the
string and then to print out the result accordingly. Expression can include
Text matching
Repetition
Branching
Pattern-composition etc.
Regular expression or RegEx in Python is denoted as RE (REs, regexes or regex pattern) are
imported through re module. Python supports regular expression through libraries. RegEx in
Python supports various things like Modifiers, Identifiers, and White space characters.
A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are
widely used in UNIX world. The Python module re provides full support for Perl-like regular
Page 151
PYTHON PROGRAMMING KG College of Arts and Science
expressions in Python. The re module raises the exception re.error if an error occurs while
compiling or using a regular expression.
Two important functions, which would be used to handle regular expressions. But a small thing
first: There are various characters, which would have special meaning when they are used in
regular expression. To avoid any confusion while dealing with regular expressions, we would
use Raw Strings as r'expression'.
The match Function :
This function attempts to match RE pattern to string with optional flags.
He e e a f f c
re.match(pattern, string, flags=0)
Regular Expression(RE) Syntax :
import re
e d e c ded P a ed f g searching and manipulation
A ed f e e f eb age Sc a g (e ac a ge a f da a f
websites)
using the expressions (w+) and (^) :
Example of w+ and ^ Expression
^ : This expression matches the start of a string
+ : T e e ion matches the alphanumeric character in the string
Here Python RegEx Example and how to use w+ and ^ expression in the code. For example, for
g , ed ca f e ec e e c de + a d^, g e e .
import re
xx = "is,education is fun"
r1 = re.findall(r"^\w+",xx)
print(r1)

Remember, if you remove +sign from the w+, the output will change, and it will only give the
first character of the first letter, i.e., [g]

Example of \s expression in re.split function


: T e pression is used for creating a space in the string
To understand how this RegEx in Python works, begin with a simple Python RegEx Example of
a f c .I ee a e, eac d g e e. f c a da e a e e
have used expression \s that allows to parse each word in the string separately.
W e c de e ec ed g e e [ e, ae, g, e, d ].
N , e ee a a e f \ e ed f .T ee a abe e , this
beca e a e e ed \ f e g, a d e a a e a a eg a c a ac e a d
e d ee e f d e g.
Similarly, there are series of other Python regular expression that can be of use in various ways
in Python like \d,\D,$,\.,\b, etc.
Here is the complete code
import re
xx = "guru99,education is fun"
r1 = re.findall(r"^\w+", xx)
print((re.split(r'\s','we are splitting the words')))
print((re.split(r's','split the words')))

5.12.1 Using regular expression methods


T e e ac age de e e a e d ac a ef e e a g.
Methods of re in Python:
re.match()
re.search()
Page 152
PYTHON PROGRAMMING KG College of Arts and Science
re.findall()
Note: Based on the regular expressions, Python offers two different primitive operations. The
match method checks for a match only at the beginning of the string while search checks for a
match anywhere in the string.
i)re.match()
re.match() function of re in Python will search the regular expression pattern and return the first
occurrence. The Python RegEx Match method checks for a match only at the beginning of the
string. So, if a match is found in the first line, it returns the match object. But if a match is found
in some other line, the Python RegEx Match function returns null.
F e a e, c de e f g c de f P e. a c () f c .T ee e +
a d \W ac e d a g e e g a d e eaf e , a g c
a ed g de f ed. T c ec a c f each element in the list or string, we run the
forloop in this Python re.match() Example.
ii)re.search(): Finding Pattern in Text
re.search() function will search the regular expression pattern and return the first occurrence.
Unlike Python re.match(), it will check all lines of the input string. The Python re.search()
f c e a a c b ec e e a e f da d f e a e f d
In order to use search() function, you need to import Python re module first and then execute the
c de. T e P e. ea c () f c a e e a e a d e ca f a g
F e a e ee f ea g S f a e e g g 99 , a e g
S f a e Testing f . F f ae e g f d e atch hence it returns the output of
P e. ea c () E a ea f d a ac , ef d g 99 c d f d
g e ce e e a N ac .

iii)re.findall()
findall() d e ed ea c f a cc e ce a match a given pattern. In contrast,
search() module will only return the first occurrence that matches the specified pattern. findall()
will iterate over all the lines of the file and will return all non-overlapping matches of pattern in
a single step.
For example, here we have a list of e-mail addresses, and we want all the e-mail addresses to be
fetched out from the list, we use the method re.findall() in Python. It will find all the e-mail
addresses from the list.

import re

list = ["guru99 get", "guru99 give", "guru Selenium"]


for element in list:
z = re.match("(g\w+)\W(g\w+)", element)
if z:
print((z.groups()))

patterns = ['software testing', 'guru99']


text = 'software testing is fun?'
for pattern in patterns:
print('Looking for "%s" in "%s" ->' % (pattern, text), end=' ')
if re.search(pattern, text):
print('found a match!')
else:
print('no match')
abc='[email protected],[email protected], [email protected]'
emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc)
for email in emails:
print(email) Page 153
PYTHON PROGRAMMING KG College of Arts and Science

5.13.CHARACTER CLASS
A "character class", or a "character set", is a set of characters put in square brackets. The
regex engine matches only one out of several characters in the character class or character set.
Place the characters where it is needed to match between square brackets. To match any vowel,
use the character set [aeiou]. A character class or set matches only a single character. The order
of the characters inside a character class or set does not matter. The results are identical. use a
hyphen inside a character class to specify a range of characters. [0-9] matches a single digit
between 0 and 9. Similarly for uppercase and lowercase letters we have the character class [A-
Za-z]

#Example
The following code finds and prints all the vowels in the given string
import re
s = 'mother of all battles'
result = re.findall(r'[aeiou]', s)
print result
Output
This gives the output
['o', 'e', 'o', 'a', 'a', 'e']

5.14 CHARACTERS AND CHARACTER CLASSES


The simplest expressions are just literal characters, such as a or 5, and if no quantifier is
explicitly given the expression is taken to be "match one occurrence." For example, the
regex tune consists of four expressions, each implicitly quantified to match once, so it matches
one t followed by one u followed by one n followed by one e, and hence matches the
strings tune and attuned.
Although most characters can be used as literals, some are special characters symbols in
the regex language that must be escaped by preceding them with a backslash (\) to use them as
literals. The special characters are \.^$?+*{}[]()|. Most of Python's standard string escapes
can also be used within regexes; for example, \n for newline and \t for tab, as well as
hexadecimal escapes for characters using the \xHH, \uHHHH, and \UHHHHHHHH syntaxes.
In many cases, rather than matching one particular character we want to match any one of a set
of characters. This can be achieved by using a character class one or more characters enclosed
in square brackets.
A character class is an expression. Like any other expression, if not explicitly quantified it
matches exactly one character (which can be any of the characters in the character class). For
example, the regex r[ea]d matches both red and radar, but not read. Similarly, to match a
single digit we can use the regex [0123456789]. For convenience we can specify a range of
characters using a hyphen, so the regex [0-9] also matches a digit. It's possible to negate the
meaning of a character class by following the opening bracket with a caret, so [^0-9] matches
any character that is not a digit.
Inside a character class, apart from the backslash (\), the special characters lose their special
meaning, although the caret (^) acquires a new meaning (negation) if it's the first character in the
character class, and otherwise is simply a literal caret. Also, the hyphen ( -) signifies a character

Page 154
PYTHON PROGRAMMING KG College of Arts and Science
range unless it's the first character, in which case it's a literal hyphen. Since some sets of
characters are required so frequently, several have shorthand forms, which are shown in Table 1.
With one exception, the shorthands can be used inside character sets; for example, the
regex [\dA-Fa-f] matches any hexadecimal digit. The exception is the period (.) which is a
shorthand outside a character class but matches a literal period inside a character class.
Table 1 Character Class Shorthands
Symbol Meaning
. Matches any character except newline, any character at all with the re.DOTALL flag, or
inside a character class matches a literal period.
\d Matches a Unicode digit, or [0-9] with the re.ASCII flag.
\D Matches a Unicode nondigit, or [^0-9] with the re.ASCII flag.
\s Matches a Unicode whitespace, or [ \t\n\r\f\v] with the re.ASCII flag.
\S Matches a Unicode non-whitespace, or [^ \t\n\r\f\v] with the re.ASCII flag.
\w Matches a Unicode "word" character, or [a-zA-Z0-9_] with the re.ASCII flag.
\W Matches a Unicode non-"word" character, or [^a-zA-Z0-9_] with the re.ASCII flag.

5.15.QUANTIFIERS IN REGULAR EXPRESSIONS :

Quantifiers specify how many instances of a character, group, or character class must be
present in the input for a match to be found. A quantifier has the form {m,n} where m and n are
the minimum and maximum times the expression to which the quantifier applies must match.
For example, both e{1,1}e{1,1} and e{2,2} match feel, but neither matches felt. Writing a
quantifier after every expression would soon become tedious, and is certainly difficult to read.
Regex language supports several convenient shorthands. If only one number is given in
the quantifier, it's taken to be both the minimum and the maximum, so e{2} is the same
as e{2,2}. As noted in the preceding section, if no quantifier is explicitly given, it's assumed to
be 1 (that is, {1,1} or {1}); therefore, ee is the same as e{1,1}e{1,1} and e{1}e{1}, so
both e{2} and ee match feel but not felt.
Having a different minimum and maximum is often convenient. For example, to
match travelled and traveled (both legitimate spellings),we could use
either travel{1,2}ed or travell{0,1}ed. The {0,1} quantification is used so often that it has its
own shorthand form, ?, so another way of writing the regex (and the one most likely to be used
in practice) is travell?ed.
Two other quantification shorthands are provided: A plus sign (+) stands for {1,n} ("at least
one") and an asterisk (*) stands for {0,n} ("any number of"). In both cases, n is the maximum
possible number allowed for a quantifier, usually at least 32767. Table 2 shows all the
quantifiers.
The + quantifier is very useful. For example, to match integers, could use \d+ to match one or
more digits. This regex could match in two places in the string 4588.91, for
example: 4588.91 and 4588.91. Sometimes typos are the result of pressing a key too long. We
could use the regex bevel+ed to match the legitimate beveled and bevelled, and the
incorrect bevellled. If we wanted to standardize on the single-l spelling, and match only oc
Table 2 Regular Expression Quantifiers
Syntax Meaning
e? or e{0,1} Greedily match zero occurrences or one occurrence of expression e.
e?? or e{0,1}? Nongreedily match zero occurrences or one occurrence of expression e.
e+ or e{1,} Greedily match one or more occurrences of expression e.
e+? or e{1,}? Nongreedily match one or more occurrences of expression e.
e* or e{0,} Greedily match zero or more occurrences of expression e.
e*? or e{0,}? Nongreedily match zero or more occurrences of expression e.
e{m} Match exactly m occurrences of expression e.
Page 155
PYTHON PROGRAMMING KG College of Arts and Science
e{m,} Greedily match at least m occurrences of expression e.
e{m,}? Nongreedily match at least m occurrences of expression e.
e{,n} Greedily match at most n occurrences of expression e.
e{,n}? Nongreedily match at most n occurrences of expression e.
e{m,n} Greedily match at least m and at most n occurrences of expression e.
e{m,n}? Nongreedily match at least m and at most n occurrences of expression e.

5.16 THE WILDCARD CHARACTER/DOT CHARACTER:


The period . (or dot) character in regex is called a wildcard because it matches any
character except for a newline.
#Example : Implementing Wildcard
a Rege = e.c e( .a )
# e a g a f ed
af e a Rege .f da ( T e ca e a a e f a a )# e : [ ca , a , a , a ,
a ]

the dot character will match just one character, c e ac f e e flat


e a e a c ed lat . T a c a ac a d , e ca e e d a bac a : \
#Ex- Wildcard with Repetition
atRegex = re.compile(r .{1,2}at )
With regard to {1, 2}, it means any 1 or 2 c a ac e (e e e ace ), f ed b at .
Matching Everything with Dot-Star
#Example : Implementing Dot-Star
The dot-star (.*) uses greedy mode. It will always try to match as much text as possible. To
match any and all text in a non-greedy fashion, use the dot, star, and question mark (.*?).
Similarly with braces, the question mark tells Python to match in a non-greedy way.

5.18 SPECIAL CHARACTERS


A special characteror sequence is a \ followed by one of the characters in the list below, and has
a special meaning: Character Description Example \A Returns a match if the specified characters
are at the beginning of the string "\AThe" \b Returns a match where the specified characters are
at the beginning or at the r"\bain" end of a word r"ain\b" \B Returns a match where the specified
characters are present, but NOT at the beginning (or at the end) of a word (the "r" in the
beginning is making sure that the string is being treated as a "raw string") r"\Bain" r"ain\B" \d
Returns a match where the string contains digits (numbers from 0-9) "\d" \D Returns a match
where the string DOES NOT contain digits "\D" \s Returns a match where the string contains a
white space character "\s" \S Returns a match where the string DOES NOT contain a white space
character "\S" \w Returns a match where the string contains any word characters (characters
from a to Z, digits from 0-9, and the underscore _ character) "\w" \W Returns a match where the
string DOES NOT contain any word characters "\W" \Z Returns a match if the specified
characters are at the end of the string "Spain\Z"

The + symbol used after the \d in the example above is used for repetition. You will see this in
some more detail in the repetition section later on...

\t - Lowercase t. Matches tab.


\n - Lowercase n. Matches newline.

Page 156
PYTHON PROGRAMMING KG College of Arts and Science
\r - Lowercase r. Matches return.
\A - Uppercase a. Matches only at the start of the string. Works across multiple lines as well.
\Z - Uppercase z. Matches only at the end of the string.
TIP: ^ and \A are effectively the same, and so are $ and \Z. Except when dealing with

5.19 GROUPING IN REGULAR EXPRESSIONS


The group feature of regular expression allows you to pick up parts of the matching text. Parts of
a regular expression pattern bounded by parenthesis () are called groups. The parenthesis does
not change what the expression matches, but rather forms groups within the matched sequence.
Using the group() function all along in this tutorial's examples. The plain match.group() without
any argument is still the whole matched text as usual.

Let's understand this concept with a simple example. Imagine you were validating email
addresses and wanted to check the user name and host. This is when you would want to create
separate groups within your matched text.

statement = 'Please contact us at: [email protected]'


match = re.search(r'([\w\.-]+)@([\w\.-]+)', statement)
if statement:
print("Email address:", match.group()) # The whole matched text
print("Username:", match.group(1)) # The username (group 1)
print("Host:", match.group(2)) # The host (group 2)
Email address: [email protected]
Username: support
Host: datacamp.com

Another way of doing the same is with the usage of <> brackets instead. This will let you create
named groups. Named groups will make your code more readable. The syntax for creating
named group is: (?P<name>...). Replace the name part with the name you want to give to your
group. The ... represent the rest of the matching syntax. See this in action using the same
example as before...

statement = 'Please contact us at: [email protected]'


match = re.search(r'(?P<email>(?P<username>[\w\.-]+)@(?P<host>[\w\.-]+))', statement)
if statement:
print("Email address:", match.group('email'))
print("Username:", match.group('username'))
print("Host:", match.group('host'))
Email address: [email protected]
Username: support
Host: datacamp.com

5.20 GREEDY MATCHES


A greedy match means that the regex engine (the one which tries to find your pattern in the
string) matches as many characters as possible. For example, the regex 'a+' will match as many
'a' s as possible in your string 'aaaa'.
#Example
>>> import re
>>> re.findall('a?', 'aaaa')
['a', 'a', 'a', 'a', '']
>>> re.findall('a*', 'aaaa')
['aaaa', '']
Page 157
PYTHON PROGRAMMING KG College of Arts and Science
>>> re.findall('a+', 'aaaa')
['aaaa']
>>> re.findall('a{3}', 'aaaa')
['aaa']
>>> re.findall('a{1,2}', 'aaaa')
['aa', 'aa']

In all cases, a shorter match would also be valid. But as the regex engine is greedy per default,
those are not enough for the regex engine.

5.21 MATCH OBJECT


A Match Object is an object containing information about the search and the result. Example
Do a search that will return a Match Object: import re txt = "The rain in Spain" x = re.search("ai",
txt) print(x) #this will print an object Output: The Match object has properties and methods used
to retrieve information about the search, and the result: .span() returns a tuple containing the
start-, and end positions of the match. .string returns the string passed into the function .group()
returns the part of the string where there was a match
Example Print the position (start- and end-position) of the first match occurrence. The regular
expression looks for any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())
#Ouput:
(12, 17)

#Example Print the string passed into the function:


import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
#Output:
The rain in Spain

5.21 GROUPING
Example Print the part of the string where there was a match. The regular expression looks for
any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
#Output:
Spain
The search() Function The search() function searches the string for a match, and returns a
Match object if there is a match. If there is more than one match, only the first occurrence of the
match will be returned: Example txt = "The rain in Spain" x = re.search("\s", txt) print("The first
white-space character is located in position:", x.start())

Page 158
PYTHON PROGRAMMING KG College of Arts and Science
5.22 GREEDY VS. NON-GREEDY MATCHING :
When a special character matches as much of the search sequence (string) as possible, it is said
to be a "Greedy Match". It is the normal behavior of a regular expression, but sometimes this
behavior is not desired:

pattern = "cookie"
sequence = "Cake and cookie"

heading = r'<h1>TITLE</h1>'
re.match(r'<.*>', heading).group()
'<h1>TITLE</h1>'
The pattern <.*> matched the whole string, right up to the second occurrence of >.

However, if you only wanted to match the first <h1> tag, you could have used the greedy
qualifier *? that matches as little text as possible.

Adding ? after the qualifier makes it perform the match in a non-greedy or minimal fashion; That
is, as few characters as possible will be matched. When you run <.*>, you will only get a match
with <h1>.

heading = r'<h1>TITLE</h1>'
re.match(r'<.*?>', heading).group()
'<h1>'

5.23 SPLITTING A STRING


The split() function returns a list where the string has been split at each match:
#Example Split at each white-space character:

import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
#o/p
['The', 'rain', 'in', 'Spain']

5.24 SUBSTITUTING
The sub() function replaces the matches with the text of your choice:
#Example Replace every white-space character with the number 9:
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
o/p
The9rain9in9Spain

#Example
import re
#Replace the first two occurrences of a white-space character with the digit 9:
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)
#output
Page 159
PYTHON PROGRAMMING KG College of Arts and Science
The9rain9in Spain

5.25 COMPILING REGULAR EXPRESSIONS


It is possible to combine a regular expression pattern into pattern objects, which can be used for
pattern matching. It also helps to search a pattern again without rewriting it. re.compile(pattern,
repl, string):
#Example
import re
pattern=re.compile('TP')
result=pattern.findall('TP Tutorialspoint TP')
print result
result2=pattern.findall('TP is most popular tutorials site of India')
print result2
#Output
['TP', 'TP'] ['TP']
SUMMARY :

It is a lot of information and concepts to grasp! The following table summarizes all

Character(s) What it does


. A period. Matches any single character except the newline character.
^ A caret. Matches a pattern at the start of the string.
\A Uppercase A. Matches only at the start of the string.
$ Dollar sign. Matches the end of the string.
\Z Uppercase Z. Matches only at the end of the string.
[] Matches the set of characters you specify within it.
\ If e c a ac e f g e bac a a ec g ed e ca e c a ac e , e e
special meaning of the term is taken.
Else the backslash () is treated like any other character and passed through.
It can be used in front of all the metacharacters to remove their special meaning.
\w Lowercase w. Matches any single letter, digit, or underscore.
\W Uppercase W. Matches any character not part of \w (lowercase w).
\s Lowercase s. Matches a single whitespace character like: space, newline, tab, return.
\S Uppercase S. Matches any character not part of \s (lowercase s).
\d Lowercase d. Matches decimal digit 0-9.
\D Uppercase D. Matches any character that is not a decimal digit.
\t Lowercase t. Matches tab.
\n Lowercase n. Matches newline.
\r Lowercase r. Matches return.
\b Lowercase b. Matches only the beginning or end of the word.
+ Checks if the preceding character appears one or more times.
* Checks if the preceding character appears zero or more times.
? C ec f e eced g c a ac e a ea e ac e e e.
Specifies a non-greedy version of +, *
{} Checks for an explicit number of times.
() Creates a group when performing matches.
<> Creates a named group when performing matches.
END OF UNIT 5
END OF ALL 5 UNITS

Page 160

You might also like