0% found this document useful (0 votes)
7 views38 pages

Unit 3 SEP Python

The document provides an overview of Python tuples and sets, highlighting their characteristics, creation methods, operations, and built-in functions. Tuples are immutable ordered collections, while sets are unordered collections that do not allow duplicates. Additionally, the document covers file handling in Python, explaining how to open, read, and write files.

Uploaded by

jndka09
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)
7 views38 pages

Unit 3 SEP Python

The document provides an overview of Python tuples and sets, highlighting their characteristics, creation methods, operations, and built-in functions. Tuples are immutable ordered collections, while sets are unordered collections that do not allow duplicates. Additionally, the document covers file handling in Python, explaining how to open, read, and write files.

Uploaded by

jndka09
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

Tuples and Sets

A Python Tuple is a group of items that are separated by commas. The indexing, nested objects,
and repetitions of a tuple are somewhat like those of a list, however unlike a list, a tuple is
immutable.

The distinction between the two is that while we can edit the contents of a list, we cannot alter the
elements of a tuple once they have been assigned.

Example

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

Features of Python Tuple

o Tuples are an immutable data type, which means that once they have been generated,
their elements cannot be changed.
o Since tuples are ordered sequences, each element has a specific order that will never
change.

Creating of Tuple:

To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (), each one
separated by a comma. Although it is not necessary to include parentheses, doing so is advised.

A tuple can contain any number of items, including ones with different data types (dictionary,
string, float, list, etc.).

Code:

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)

Output:

Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Tuples can be constructed without using parentheses. This is known as triple packing.

Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)

Operations on Tuples
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior
chapter −

Python Expression Results Description


len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration


Built in Functions on Tuples
Python includes the following tuple functions −

[Link]. Function with Description

1 cmp(tuple1, tuple2)
Compares elements of both tuples.

2 len(tuple)
Gives the total length of the tuple.

3 max(tuple)
Returns item from the tuple with max value.

4 min(tuple)
Returns item from the tuple with min value.

5 tuple(seq)
Converts a list into tuple.

Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was
found

Example 1: Using the Tuple count() method


# Creating tuples

Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)

Tuple2 = ('python', 'geek', 'python',

'for', 'java', 'python')

# count the appearance of 3

res = [Link](3)

print('Count of 3 in Tuple1 is:', res)

# count the appearance of python

res = [Link]('python')

print('Count of Python in Tuple2 is:', res)

Output:
Count of 3 in Tuple1 is: 3
Count of Python in Tuple2 is: 3
Index() Method

The Index() method returns the first occurrence of the given element from the tuple.

Syntax:

[Link](element, start, end)

Parameters:

element: The element to be searched.

start (Optional): The starting index from where the searching is started

end (Optional): The ending index till where the searching is done

Note: This method raises a ValueError if the element is not found in the tuple.
Example 1: Using Tuple Index() Method

# Creating tuples

Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)

# getting the index of 3

res = [Link](3)

print('First occurrence of 3 is', res)

# getting the index of 3 after 4th

# index

res = [Link](3, 4)

print('First occurrence of 3 after 4th index is:', res)

Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5
SET
A Set in Python programming is an unordered collection data type that is iterable, mutable and
has no duplicate elements.

Set are represented by { } (values enclosed in curly braces)

The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set. This is based on a data structure
known as a hash table. Since sets are unordered, we cannot access items using indexes as we do
in lists.

Internal working of Set

This is based on a data structure known as a hash table. If Multiple values are present at the
same index position, then the value is appended to that index position, to form a Linked List.
In, Python Sets are implemented using a dictionary with dummy variables, where key beings the
members set with greater optimizations to the time complexity.

Set Implementation:

Sets with Numerous operations on a single HashTable:


Creating Sets
 You can create an empty set in python by using the set() function.
 empty set can be created using the curly braces {}, but notice that python interprets
empty curly braces as a dictionary.

 A set can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as
its elements.
 Let's see an example,
 # create a set of integer type
 student_id = {112, 114, 116, 118, 115}
 print('Student ID:', student_id)


 # create a set of string type
 vowel_letters = {'a', 'e', 'i', 'o', 'u'} print('Vowel
 Letters:', vowel_letters)


 # create a set of mixed data types mixed_set =
{'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)

Operations On Sets

Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, subtraction, and symmetric difference.

Union of Two Sets

The union of two sets A and B include all the elements of set A and B.

Set Union in Python


We use the | operator or the union() method to perform the set union operation. For example,
# first set A =
{1, 3, 5}

# second set B
= {0, 2, 4}

# perform union operation using | print('Union


using |:', A | B)

# perform union operation using union()


print('Union using union():', [Link](B)) Run Code

Output

Union using |: {0, 1, 2, 3, 4, 5}


Union using union(): {0, 1, 2, 3, 4, 5}

Note: A|B and union() is equivalent to A ⋃ B set operation.

Set Intersection

The intersection of two sets A and B include the common elements between set A and B.

Set Intersection in Python


In Python, we use the & operator or the intersection() method to perform the set intersection
operation. For example,
# first set A =
{1, 3, 5}

# second set B
= {1, 2, 3}

# perform intersection operation using &


print('Intersection using &:', A & B)

# perform intersection operation using intersection() print('Intersection


using intersection():', [Link](B)) Run Code

Output
Intersection using &: {1, 3}
Intersection using intersection(): {1, 3}

Note: A&B and intersection() is equivalent to A ⋂ B set operation.

Difference between Two Sets

The difference between two sets A and B include elements of set A that are not present on set B.

Set Difference in Python


We use the - operator or the difference() method to perform the difference between two sets. For
example,
# first set A =
{2, 3, 5}

# second set B
= {1, 2, 6}

# perform difference operation using &


print('Difference using &:', A - B)

# perform difference operation using difference() print('Difference


using difference():', [Link](B)) Run Code

Output

Difference using &: {3, 5}


Difference using difference(): {3, 5}

Note: A - B and [Link](B) is equivalent to A - B set operation.

Set Symmetric Difference

The symmetric difference between two sets A and B includes all elements of A and B without
the common elements.
Set Symmetric Difference in Python
In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric
difference between two sets. For example,
# first set A =
{2, 3, 5}

# second set B
= {1, 2, 6}

# perform difference operation using & print('using ^:', A ^


B)

# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Run Code
Output

using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.
Function Description

all() Returns True if all elements of the set are true (or if the set is empty).

Returns True if any element of the set is true. If the set is empty, returns
any()
False.

Returns an enumerate object. It contains the index and value for all the
enumerate()
items of the set as a pair.

len() Returns the length (the number of items) in the set.


max() Returns the largest item in the set.

min() Returns the smallest item in the set.

Returns a new sorted list from elements in the set(does not sort the set
sorted()
itself).

sum() Returns the sum of all elements in the set.

Set Methods

There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with the set objects:

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

Returns the difference of two or more sets as a new


difference()
set

difference_update() Removes all elements of another set from this set

Removes an element from the set if it is a member.


discard()
(Do nothing if the element is not in set)

intersection() Returns the intersection of two sets as a new set

Updates the set with the intersection of itself and


intersection_update()
another

isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element.


pop()
Raises KeyError if the set is empty
Removes an element from the set. If the element is
remove()
not a member, raises a KeyError

Returns the symmetric difference of two sets as a


symmetric_difference()
new set

Updates a set with the symmetric difference of itself


symmetric_difference_update()
and another

union() Returns the union of sets in a new set

update() Updates the set with the union of itself and others

File Handling
The file handling plays an important role when the data needs to be stored permanently into the
file. A file is a named location on disk to store related information. We can access the stored
information (non-volatile) after the program termination.

In Python, files are treated in two modes as text or binary. The file may be in the text or binary
format, and each line of a file is ended with the special character.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
o Close the file

Types of Files in Python


1. Text File
2. Binary File

1. Text File
 Text file store the data in the form of characters.
 Text file are used to store characters or strings.
 Usually we can use text files to store character data
 eg: [Link]
Ⅳ SEM BCA PYTHON

2. Binary File
 Binary file store entire data in the form of bytes.
 Binary file can be used to store text, image, audio and video.
 Usually we can use binary files to store binary data like images,video files, audio files etc
Operations on Files-
1. Open
Before performing any operation on the file like reading or writing, first, we have to open that
file. For this, we should use Python’s inbuilt function open() but at the time of opening, we have
to specify the mode, which represents the purpose of the opening file.

f = open(filename, mode)

Where the following mode is supported:

 r: open an existing file for a read operation.


 w: open an existing file for a write operation. If the file already contains some data then it
will be overridden but if the file is not present then it creates the file as well.
 a: open an existing file for append operation. It won’t override existing data.
 r+: To read and write data into the file. The previous data in the file will be overridden.
 w+: To write and read data. It will override existing data.
 a+: To append and read data from the file. It won’t override existing data.

2. Read
There is more than one way to read a file in Python

Eample 1: The open command will open the file in the read mode and the for loop will print each
line present in the file.

# a file named "geek", will be opened with the reading mode.

file = open('[Link]', 'r')

# This will print every line one by one in the file

for each in file:

Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 13


print (each)

Output:

Hello world

GeeksforGeeks

123 456

Example 2: In this example, we will extract a string that contains all characters in the file then
we can use [Link]().

# Python code to illustrate read() mode

file = open("[Link]", "r")

print ([Link]())

Output:

Hello world

GeeksforGeeks

123 456

Example 3: In this example, we will see how we can read a file using the with statement.

Python3

# Python code to illustrate with()

with open("[Link]") as file:

data = [Link]()

print(data)
Output:

Hello world

GeeksforGeeks

123 456

3. Write
To write some text to a file, we need to open the file using the open method with one of the
following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if
no file exists.

Example:

# open the [Link] in append mode. Create a new file if no such file exists.
fileptr = open("[Link]", "w")
# appending the content to the file
[Link]('''''Python is the modern day language. It makes things so simple.
It is the fastest-growing programing language''')
# closing the opened the file
[Link]()

Output:

[Link]

Python is the modern-day language. It makes things so simple. It is the faste fastest-
growing programing language

4. Close Files
Once all the operations are done on the file, we must close it through our Python script using
the close() method. Any unwritten information gets destroyed once the close() method is called on
a file object.

We can perform any operation on the file externally using the file system which is the currently
opened in Python; hence it is good practice to close the file once all the operations are done.
The syntax to use the close() method is given below.

Syntax

1. [Link]()

File Names and Paths


In Python, we have various built-in functions which can help us to get the path of the
running .py file(the file on which we are currently working). These functions are path.
cwd(), [Link](), [Link]().absolute(), [Link], and [Link].

An absolute path specifies the location of the file relative to the root directory or it contains the
complete location of the file or directory, whereas relative paths are related to the current
working directory.

Absolute path: C:/users/Dell/docs/[Link]

If our current working directory(CWD) is C:/users/Dell/, then the relative


path to [Link] would be docs/[Link]

CWD + relative path = absolute path

Different Ways to Get Path of File in Python


Using [Link]():

[Link]() is used to get the current path. The pathlib module provides us with the
function cwd() by which we can fetch the current working directory.

Code:

from pathlib import Path


print([Link]())

Output:

C:\Users\Dell

Using [Link]():

The function [Link]() returns the current working directory. Here getcwd stands for Get
Current Working Directory.
Code:

import os
cwd = [Link]() # This fn will return the Current Working Directory
print("Current working directory:", cwd)

Output:

Current working directory: C:\Users\Dell

Using [Link]().absolute():

[Link]().absolute() is used to get the current path. The pathlib module provides us with
the function absolute() by which we can fetch the path of the current working directory.

Code:

import pathlib
print([Link]().absolute())

Output:

C:\Users\Dell

Using [Link]():

The OS module provides numerous functions. [Link]() returns the name of the
currently running Python file. And if we want to get the whole path of the directory in which our
Python file is residing, then we can use [Link]().

Code:

import os
print('File name:', [Link]( file ))
print('Directory Name: ', [Link]( file ))

Output:

File name: [Link]


Directory Name: c:\Users\Dell\Desktop\Lang

Using [Link]():

[Link]() function is very much the same as the [Link]() function. In


the [Link]() function, we were getting the name of the python file, but using
the [Link]() function we will get the absolute path of the Python file.
Code:

import os
print('absPath: ', [Link]( file ))
print('absDirname: ', [Link]([Link]( file )))

Output:

absPath: c:\Users\Dell\OneDrive\Desktop\Lang\[Link]
absDirname: c:\Users\Dell\OneDrive\Desktop\Lang

Format Operator:
The argument of write has to be a string, so if we want to put other values in a file, we have to
convert them to strings. The easiest way to do that is with str:

x = 52
fout = open('[Link]', 'w')
[Link](str(x))
An alternative is to use the format operator, %. When applied to integers, % is the modulus
operator. But when the first operand is a string, % is the format operator.

The first operand is the format string, which contains one or more format sequences, which
specify how the second operand is formatted. The result is a string.

For example, the format sequence '%d' means that the second operand should be formatted as an
integer (d stands for “decimal”):

>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42.

A format sequence can appear anywhere in the string, so you can embed a value in a sentence:

>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has to be a tuple.
Each format sequence is matched with an element of the tuple, in order.

The following example uses '%d' to format an integer, '%g' to format a floating-point number
(don’t ask why), and '%s' to format a string:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')


'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple has to match the number of format sequences in the string.
Also, the types of the elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation
In the first example, there aren’t enough elements; in the second, the element is the wrong type.
Classes in Python:
A class is a user-defined data type that contains both the data itself and the methods that may be used to
manipulate it. In a sense, classes serve as a template to create objects. They provide the characteristics and
operations that the objects will employ.

Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms, doors,
windows, etc. we can make as many buildings as we want, based on these details. Hence, the building can
be seen as a class, and we can create as many objects of this class.

Creating Classes in Python


A class can be created by using the keyword class, followed by the class name.

Syntax
class ClassName:
#statement_suite

We must notice that each class is associated with a documentation string which can be accessed by
using <class-name>. doc . A class contains a statement suite including fields, constructor, function, etc.

class Person:
def init (self, name, age):
# This is the constructor method that is called when creating a new Person object
# It takes two parameters, name and age, and initializes them as attributes of the object
[Link] = name
[Link] = age
def printMe(self):
# This is a method of the Person class that prints a message
print("Hello, my name is " + [Link])

Name and age are the two properties of the Person class. Additionally, it has a function called printMe that
prints a msg.

Objects in Python:
An object is a particular instance of a class with unique characteristics and functions. After a class has been
established, you may make objects based on it. By using the class constructor, you may create an object of
a class in Python. The object's attributes are initialised in the constructor, which is a special procedure with
the name init .
Syntax:
# Declare an object of a class
object_name = Class_Name(arguments)
class Person:
def init (self, name, age):
[Link] = name
[Link] = age
def printMe(self):
print("Hello, my name is " + [Link])
# Create a new instance of the Person class and assign it to the variable person1
person1 = Person("Ayan", 25)
[Link]()

Output: "Hello, my name is Ayan"

The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables. We can use
anything instead of self, but it must be the first parameter of any function which belongs to the class.

_ _init_ _ method
In order to make an instance of a class in Python, a specific function called init is called. Although it is used
to set the object's attributes, it is often referred to as a constructor.

The self-argument is the only one required by the init method. This argument refers to the newly generated
instance of the class. To initialise the values of each attribute associated with the objects, you can declare
extra arguments in the init method.

Class and Instance Variables


All instances of a class exchange class variables. They function independently of any class methods and may
be accessed through the use of the class name. Here's an illustration:

class Person:
count = 0 # This is a class variable
def init (self, name, age):
[Link] = name # This is an instance variable
[Link] = age
[Link] += 1 # Accessing the class variable using the name of the class
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
Output: 2

Whereas, instance variables are specific to each instance of a class. They are specified using the self-
argument in the init method. Here's an illustration:
class Person:
def init (self, name, age):
[Link] = name # This is an instance variable
[Link] = age
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
print([Link])
Output: Ayan
30
Class variables are created separately from any class methods and are shared by all class copies. Every
instance of a class has its own instance variables, which are specified in the init method utilising the self-
argument.

Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance members of the
class. In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in
Python. It is used to create an object.

Constructors can be of two types.


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.

Creating the constructor in python


In Python, the method the init () simulates the constructor of the class. This method is called when the class
is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method
of the class.
We can pass any number of arguments at the time of creating the class object, depending upon
the init () definition. It is mostly used to initialize the class attributes. Every class must have a constructor,
even if it simply relies on the default constructor.

Consider the following example to initialize the Employee class attributes.


class Employee:
def init (self, name, id):
[Link] = id
[Link] = name
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
[Link]()
# accessing display() method to print employee 2 information
[Link]()

Output:

ID: 101
Name: John
ID: 102
Name: David
Counting the number of objects of a class
The constructor is called automatically when we create the object of the class. Consider the following
example.
class Student:
count = 0
def init (self):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])
Output:
The number of students: 3

Python Non-Parameterized Constructor


The non-parameterized constructor uses when we do not want to manipulate the value or the constructor
that has only self as an argument. Consider the following example.
class Student:
# Constructor - non parameterized
def init (self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link]("John")

Python Parameterized Constructor


The parameterized constructor has multiple parameters along with the self. Consider the following
example.
class Student:
# Constructor - parameterized
def init (self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link])
student = Student("John")
[Link]()
Output:
This is parametrized constructor
Hello John

Python Default Constructor


When we do not include the constructor in the class or forget to declare it, then that becomes the default
constructor. It does not perform any task but initializes the objects. Consider the following example.
class Student:
roll_num = 101
name = "Eshwar"
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()
Output:
101 Eshwar

Python built-in class functions


The built-in functions defined in the class are described in the following table.

SN Function Description

1 getattr(obj,name,default) It is used to access the attribute of the object.

2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.

4 hasattr(obj, name) It returns true if the object contains some specific attribute.

getattr(obj,name,default)
class Student:
def__init__(self,name)
[Link]=name
s=Student(“Ram”)
print(getattr(s,”name”))

setattr(obj,name,value)
class Student:
def__init__(self,name)
[Link]=name
s=Student(“Ram”)
setattr(s,”name”,”shyam”)
print([Link])

delattr(obj,name)
s=Student(“Ram”)
delattr(s,”name”)

hasattr(obj,name)
s=Student(“Ram”)
print(hasattr(s,”name”)
print(hasattr(s,”age”) output: True
False

Multiple Objects in Python


We can create a list of objects in Python by appending class instances to the list. By this, every index in the
list can point to instance attributes and methods of the class and can access them. If you observe it closely,
a list of objects behaves like an array of structures in C. Let’s try to understand it better with the help of
examples.

class Student:
def init (self, name, roll):
[Link] = name
[Link] = roll
# creating list
list = []
# appending instances to list
[Link](Student('Akash', 2))
[Link](Student('Deependra', 40))
[Link](Student('Reena', 44))
[Link](Student('Veena', 67))

# Accessing object value using a for loop


for obj in list:
print([Link], [Link], sep=' ')

print("")
# Accessing individual elements
print(list[3].name)
print(list[2].name)
print(list[1].name)
print(list[0].name)

Output
Akash 2
Deependra 40
Reena 44
Veena 67

Veena
Reena
Deependra
Akash

Python program to pass objects as arguments and return objects from function
Python allows its programmers to pass objects to method. And also return objects from a method. Here is a
program to illustrate this,
class TwoNum:
def GetNum(self):
self. x = int(input("Enter value of x : "))
self. y = int(input("Enter value of y : "))

def PutNum(self):
print("value of x = ", self. x,"value of y = ", self. y, )

def Add(self,T):
R=TwoNum()
R. x=self. x+T. x
R. y=self. y+T. y
return R

obj1 = TwoNum()
obj2 = TwoNum()
print("Enter values of object 1 ")
[Link]()
print("Enter values of object 2 ")
[Link]()
obj3 = [Link](obj2)
print("Values of object 1 ")
[Link]()
print("Values of object 2 ")
[Link]()
print("Values of object 3 (sum object) ")
[Link]()
Output:
Enter values of object 1
Enter value of x : 43
Enter value of y : 65
Enter values of object 2
Enter value of x : 34
Enter value of y : 65
Values of object 1
value of x = 43 value of y = 65
Values of object 2
value of x = 34 value of y = 65
Values of object 3 (sum object)
value of x = 77 value of y = 130

Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to
the program because we can use an existing class to create a new class instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members and functions
defined in the parent class. A child class can also provide its specific implementation to the functions of the
parent class. In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name. Consider the following syntax to inherit a base class into the derived class.

Syntax
class derived-class(base class):
<class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following
syntax.
class derive-class(<base class 1>, <base class 2>,.......<base class n>):
<class - suite>
Single Inheritance
A child class inherits from only one parent class
Syntax:

class base:
<class suite>
class derived:
<class suite>

Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is
achived when a derived class inherits another derived class. There is no limit on the number of levels up to
which, the multi-level inheritance is achived in python.

Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.

Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2,........BaseN):


<class-suite>

Example
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([Link](10,20))
print([Link](10,20))
print([Link](10,20))
Output:
30
200
0.5

Multipath Inheritance
When a class is derived from two or more classes which are derived from the same base class then such type
of inheritance is called multipath inheritance.

Syntax
class Base A:
def show(self):
print(“class A”)
class B(A):
def display(self):
print(“class B”)
class C(A):
def print_msg(self):
print(“class C”)
class D(B,C):
def output(self):
print(class D”)
obj=D()
[Link]()
[Link]()
obj.print_msg()
[Link]()

output
class A
class B
class C
class D

Here class 'D' derived from classes 'B' and 'C', which are derived from same base class 'A'.

Encapsulation
Encapsulation is one of the key concepts of object-oriented languages like Python, Java, etc. Encapsulation
is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together
within a single unit from being modified by accident.
Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data (methods)
together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can
be accessed only through the methods of their current class.
Encapsulation Example
Let’s say we have a company selling courses to students, engineers and professionals. The different sections
of this company include, operations, finance, accounts, sales, etc. Now, if an employee from the accounts
section needs the records of sales in 2022, then he/ she cannot directly access it.
To access, the employee of the account sections needs to get permission from the sales section team member.
Therefore, the sales data is hidden from other departments, In the same way, the financials of the company
is accessible to only the finance data and is hidden from other sections. The accounts, sales, finance,
operations, marketing, etc. data is hidden from other sections.
Access Modifiers in Python : Public, Private and Protected
Various object-oriented languages like C++, Java, Python control access modifications which are used to
restrict access to the variables and methods of the class. Most programming languages has three forms of
access modifiers, which are Public, Protected and Private in a class.

Python uses ‘_’ symbol to determine the access control for a specific data member or a member function of
a class. Access specifiers in Python have an important role to play in securing data from unauthorized access
and in preventing it from being exploited.

A Class in Python has three types of access modifiers:


 Public Access Modifier
 Protected Access Modifier
 Private Access Modifier
Public Access Modifier:
The members of a class that are declared public are easily accessible from any part of the program.
All data members and member functions of a class are public by default.
Protected Access Modifier:
The members of a class that are declared protected are only accessible to a class derived from it. Data
members of a class are declared protected by adding a single underscore ‘_’ symbol before the data member
of that class.
Private Access Modifier:
The members of a class that are declared private are accessible within the class only, private access
modifier is the most secure access modifier. Data members of a class are declared private by adding a double
underscore ‘ ’ symbol before the data member of that class.

Below is a program to illustrate the use of all the above three access modifiers (public,
protected, and private) of a class in Python:

class Super:
# public data member
var1 = None
# protected data member
_var2 = None
# private data member
var3 = None

# constructor
def init (self, var1, var2, var3):
self.var1 = var1
self._var2 = var2
self ___ ar3 = var3

# public member function


def displayPublicMembers(self):
# accessing public data members
print("Public Data Member: ", self.var1)

# protected member function


def _displayProtectedMembers(self):
# accessing protected data members
print("Protected Data Member: ", self._var2)

# private member function


def displayPrivateMembers(self):
# accessing private data members
print("Private Data Member: ", self. var3)

# public member function


def accessPrivateMembers(self):
# accessing private member function
self. displayPrivateMembers()

# derived class
class Sub(Super):
# constructor
def init (self, var1, var2, var3):
Super. init (self, var1, var2, var3)
# public member function
def accessProtectedMembers(self):
# accessing protected member functions of super class
self._displayProtectedMembers()

# creating objects of the derived class


obj = Sub("College", 4, " College!")

# calling public member functions of the class


[Link]()
[Link]()
[Link]()

# Object can access protected member


print("Object is accessing protected member:", obj._var2)

# object can not access private member, so it will generate Attribute error
#print(obj. var3)
Output:
Public Data Member: College
Protected Data Member: 4
Private Data Member: College!

Polymorphism in Python
Polymorphism refers to having multiple forms. Polymorphism is a programming term that refers to the use
of the same function name, but with different signatures, for multiple types.

Example of in-built polymorphic functions:


# Python program for demonstrating the in-built poly-morphic functions
# len() function is used for a string
print (len("SVCCollege"))
# len() function is used for a list
print (len([110, 210, 130, 321]))
Output:
10
4
Polymorphism with Class Methods
Below is an example of how Python can use different types of classes in the same way. For loops that iterate
through multiple objects are created. Next, call the methods without caring about what class each object
belongs to. These methods are assumed to exist in every class.

class xyz():
def websites(self):
print("Google is a website out of many availabe on net.")
def topic(self):
print("Python is out of many topics about technology.")
def type(self):
print("Google is an developed website.")

class PQR():
def websites(self):
print("Pinkvilla is a website out of many availabe on net. .")
def topic(self):
print("Celebrities is out of many topics.")
def type(self):
print("pinkvilla is a developing website.")

obj_jtp = xyz()
obj_pvl = PQR()
for domain in (obj_jtp, obj_pvl):
[Link]()
[Link]()
[Link]()
Output:
Google is a website out of many availabe on net.
Python is out of many topics about technology.
Google is an developed website.
Pinkvilla is a website out of many availabe on net.
Celebrities is out of many topics.
pinkvilla is a developing website.

What is Operator Overloading in Python


The operator overloading in Python means provide extended meaning beyond their predefined 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:
print (14 + 32)
# Now, we will concatenate the two strings
print ("SVC" + "College")
# We will check the product of two numbers
print (23 * 14)
# Here, we will try to repeat the String
print ("X Y Z " * 3)
Output:
46
SVCCollege
322
XYZXYZXYZ

How to Overload the Operators in Python?


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.

How to Perform Binary "+" Operator in Python:


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 the
operator is as simple as the behaviour of the function or method defined.

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.

Program : Simply adding two objects.


class example:
def init (self, X):
self.X = X
# adding two objects
def add (self, U):
return self.X + U.X
object_1 = example( int( input( print ("Please enter the value: "))))
object_2 = example( int( input( print ("Please enter the value: "))))
print (": ", object_1 + object_2)
object_3 = example(str( input( print ("Please enter the value: "))))
object_4 = example(str( input( print ("Please enter the value: "))))
print (": ", object_3 + object_4)
Output:
Please enter the value: 23
Please enter the value: 21
: 44
Please enter the value: JSS
Please enter the value: College
: JSSCollege

Python magic functions used for operator overloading:


Binary Operators:

Operator Magic Function

+ add (self, other)

- sub (self, other)

* mul (self, other)

/ truediv (self, other)

// floordiv (self, other)

% mod (self, other)

** pow (self, other)

>> rshift (self, other)

<< lshift (self, other)

& and (self, other)

| or (self, other)

^ xor (self, other)

Comparison Operators:

Operator Magic Function

< LT (SELF, OTHER)

> GT (SELF, OTHER)

<= LE (SELF, OTHER)

>= GE (SELF, OTHER)

== EQ (SELF, OTHER)

!= NE (SELF, OTHER)
Assignment Operators:

Operator Magic Function

-= ISUB (SELF, OTHER)

+= IADD (SELF, OTHER)

*= IMUL (SELF, OTHER)

/= IDIV (SELF, OTHER)

//= IFLOORDIV (SELF, OTHER)

%= IMOD (SELF, OTHER)

**= IPOW (SELF, OTHER)

>>= IRSHIFT (SELF, OTHER)

<<= ILSHIFT (SELF, OTHER)

&= IAND (SELF, OTHER)

|= IOR (SELF, OTHER)

^= IXOR (SELF, OTHER)

Unary Operator:

Operator Magic Function

- NEG (SELF, OTHER)

+ POS (SELF, OTHER)

~ INVERT (SELF, OTHER)

You might also like