BPP Unit 4
BPP Unit 4
DATA STRUCTURES
Organizing, managing and storing data is important as it enables easier access and
efficient modifications. Data Structures allows you to organize your data in such a way that
enables you to store collections of data, relate them and perform operations on them
accordingly.
Python has implicit support for Data Structures which enable you to store and access
data. These structures are called List, Dictionary, Tuple and Set. these Data Structures are
built-in with Python which makes programming easier and helps programmers use them to
obtain solutions faster.
Sequence
Sequences allow you to store multiple values in an organized and efficient fashion.
The different Python data structures can be divided into two categories based on the ordering
of items: Sequences and Collections. Elements in sequences come out in the same order as
it is inserted, however ordering in collections is not preserved.
In Python programming, sequences are a generic term for an ordered set which
means that the order in which we input the items will be the same when we access them.
Python supports six different types of sequences. These are strings, lists, tuples, byte
sequences, byte arrays, and range objects.
A sequence is a positionally ordered collection of items. And you can refer to any
item in the sequence by using its index number e.g., s[0] and s[1]. In Python, the sequence
index starts at 0, not 1. So the first element is s[0] and the second element is s[1]. If the
sequence s has n items, the last item is s[n-1].
The mutable sequence types are lists and bytearrays while the immutable sequence
types are strings, tuples, range, and bytes. A sequence can be homogeneous or heterogeneous.
In a homogeneous sequence, all elements have the same type. For example, strings are
homogeneous sequences where each element is of the same type. Lists, however, are
heterogeneous sequences where you can store elements of different types including integer,
strings, objects, etc. In general, homogeneous sequence types are more efficient than
heterogeneous in terms of storage and operations.
Lists
In Python, lists are ordered collections of items that allow for easy use of a set of data.
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements. Each element or value that is inside of a list is called an item. List values are placed
in between square brackets [ ], separated by commas. It is good practice to put a space
between the comma and the next value. The values in a list do not need to be unique (the
same value can be repeated). Empty lists do not contain any values within the square
brackets.
In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. The index must be an integer. Each item in a list has an assigned index
value. It is important to note that python is a zero indexed based language. All this means is
that the first item in the list is at index 0.
Output
p
• step allows you to select nth item within the range start to stop.
Program to demonstrate the slice operations used to access the elements of the list
my_list = [1, 2, 3, 4, 5]
print(my_list[:])
print(my_list[2:])
print(my_list[:2])
print(my_list[2:4])
print(my_list[::2])
print(my_list[::-2])
print(my_list[1:4:2])
Output
[1, 2, 3, 4, 5]
[3, 4, 5]
[1, 2]
[3, 4]
[1, 3, 5]
[5, 3, 1]
[2, 4]
update values in a List
In Python, lists are mutable. It means we can change the list’s contents by adding, updating,
or removing elements from the list. In Python, we can use list methods append(), insert(), and
extend() to add the elements to the list. we can use list methods clear(), pop(), and remove()
to remove the elements from the list.
Output:
Dell
HP
Leveno
Asus
Toshiba
# Declare list
listdata = [89, 56, 90, 34, 89, 12]
# Insert data in the 2nd position
listdata.insert(2, 23)
# Displaying list after inserting
print("The list elements are")
for i in range(0, len(listdata)):
print(listdata[i])
Output:
89
56
23
90
34
89
12
Output:
html
CSS
JavaScript
JQuery
PHP
Laravel
CodeIgniter
Output:
Remove item from the list using del method and clear() method
Output:
[]
Nested lists:
A nested list is a list of lists, or any list that has another list as an element (a sublist). They
can be helpful if you want to create a matrix or need to store a sublist along with other data
types.
# creating list
subList = nestedList[2]
# access the first element inside the inner list:
element = nestedList[2][0]
Output:
Cloning Lists
If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word copy. The easiest way to clone a list is to use the slice
operator.
original_list = [1, 2, 3]
copy_list = original_list[:]
copy_list[0] = 2
print(original_list)
print(copy_list)
Output:
[1, 2, 3]
[2, 2, 3]
First of all, we must aware with the Stack - the stack is a linear data structure that works
on LIFO mechanism i.e. Last In First Out (that means Last inserted item will be removed
(popped) first).
In Python, we can implement a stack by using list methods as they have the capability to
insert or remove/pop elements from the end of the list.
print (stack)
# push operation
stack.append(40)
stack.append(50)
print (stack)
# push operation
print (stack)
Output
stack elements:
50 is removed/popped...
40 is removed/popped...
30 is removed/popped...
[10, 20]
Queue
A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends
hence we can easily add elements to the back and can remove elements from the front.
Operations on Queue
o Addition - It adds the element in a queue and takes place at the rear end, i.e., at the
back of the queue.
Characteristics
o Duplicacy is allowed.
Code
import queue
L = queue.Queue(maxsize=10)
L.put(9)
L.put(6)
L.put(7)
L.put(4)
# of the Queue
print(L.get())
print(L.get())
print(L.get())
print(L.get())
Output:
List Comprehension
List Comprehension is defined as an elegant way to define, create a list in Python and
consists of brackets that contains an expression followed by for clause. It is efficient in both
computationally and in terms of coding space and time.
Signature
Example
letters = []
letters.append(letter)
print(letters)
Output:
Example
print( letters)
Output:
There are multiple ways through which we can iterate the list in python programming.
The easiest method to iterate the list in python programming is by using them for a loop. The
method of the iterating list using for loop is as given below
list = [1, 2, 3, 4, 5]
for i in list:
print(i)
output
Another method to iterate the list while programming in python is by using the loop and
range() function together. Iterating the list using this method is not recommended if iteration
using for loop(method 1) is possible. The method to do so is as given below:
list = [1, 2, 3, 4, 5]
length = len(list)
for i in range(length):
print(list[i])
output
There are few times when you may need the display the index of the element along with the
element in the list itself. In such cases, we use the enumerate() function for the iteration of the
list. The method to use the enumerate() function to iterate the list is as given below:
list = [1, 3, 5, 7, 9]
0, 1
1, 3
2, 5
3, 7
4, 9
Using an iterator:
use an iterator to manually loop over the iterable it came from. A repeated passing of iterator
to the built-in function next()returns successive items in the stream. Once, when you
consumed an item from an iterator, it’s gone. When no more data are available
a StopIteration exception is raised.
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
10
20
30
Functional Programming
The map() function is a higher-order function. As previously stated, this function accepts
another function and a sequence of ‘iterables’ as parameters and provides output after
applying the function to each iterable in the sequence. It has the following syntax:
The function is used to define an expression which is then applied to the ‘iterables’. User-
defined functions and lambda functions can both be sent to the map function.
User-defined functions can be sent to the map() method. The user or programmer is the only
one who can change the parameters of these functions.
EXAMPLE
def function(a):
return a*a
x = map(function, (1,2,3,4)) #x is the map object
print(x)
print(set(x))
OUTPUT
{16, 1, 4, 9}
x is a map object, as you can see. The map function is displayed next, which takes
“function()” as a parameter and then applies “a * a” to all ‘iterables’. As a result, all iterables’
values are multiplied by themselves before being returned.
Functions with no name are known as lambda functions. These functions are frequently used
as input to other functions. Let’s try to integrate Lambda functions into the map() function.
EXAMPLE
tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61)
print(newtuple)
OUTPUT
(8, 10, 25, 100, 57, 65, 80, 26, 76, 64)
The filter() function is used to generate an output list of values that return true when the
function is called. It has the following syntax:
This function like map(), can take user-defined functions and lambda functions as parameters.
EXAMPLE
def func(x):
if x>=3:
return x
y = filter(func, (1,2,3,4))
print(y)
print(list(y))
OUTPUT
[3, 4]
EXAMPLE
print(list(y))
OUTPUT
[3, 4]
The reduce() function applies a provided function to ‘iterables’ and returns a single value, as
the name implies.
EXAMPLE
OUTPUT
187
The reduce function in the preceding example adds each iterable in the list one by one and
returns a single result. The Python functions map(), filter(), and reduce() can all be used
together.
Tuples
A Python tuple is an immutable ordered sequence of items. In other words, existing objects in
the sequence cannot be modified, and new elements cannot be added once the sequence is
created. A tuple consists of several values separated by commas. Unlike a Python list, tuples
are enclosed within parentheses “( )”.
A Python tuple is created by using parentheses separated by commas. A tuple can hold
multiple data types.
Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is
the same as returning multiple values. For example, if you want to divide two integers and
compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better
to compute them both at the same time.
The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t
(2, 1)
You can access items of a tuple using index just like a list. Provide an index in square
brackets next to the reference to the tuple, and it returns the item in tuple present at the index.
Index of first element is zero, and the index of second element is one.
Slicing operation in tuples
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)
print(my_data[2:5])
print(my_data[:4])
print(my_data[4:])
print(my_data[4:-1])
print(my_data[:])
Output:
In tuples we can not update or change the value, because tuples are immutable means can't
change or modifie but only can be updated if their are more then one tuple. Only we take
portions of existing tuples to create a new tuples.
tuple3 = tuple1+tuple2
print tuple3
Output:
Since tuple is an immutable data structure , you cannot delete the elements from the tuple.
Ofcourse you can create a new tuple that has all the elements in your tuple except the ones
you don’t want.
number=(1,2.5,1.2,3)
del (number[0])
print(number)
Output
In the above Example , we are deleting element [0] of tuple variable ‘number’ by del
(number[0]) so in output ,we got type error i.e. ‘tuple’ object doesn’t support item deletion.
Example (2): Delete multiple element of tuple
alphabet=('a','b','c','d','e')
del(alphabet[1:3])
print(alphabet[1:3])
Output
In the above Example , we are deleting multiple element as 1st ,2nd and 3rd index in alphabet
by ‘del(alphabet[1:3])’ so output display the value of 4th and 5th index only as [‘d’, ‘e’].
mytuple=(1,'Python',5.2,'language!')
del (mytuple)
print(mytuple)
Output
In the above Example , we are deleting tuple variable ‘mytuple’ by del (mytuple) so, we
received the output as error i.e. name ‘mytuple’ is not defined because ‘mytuple’ is already
deleted in the previous step.
TUPLE ASSIGNMENT
The left side is a tuple of variables; the right side is a tuple of values.
All the expressions on the right side are evaluated before any of the assignments. This feature
makes tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right have to
be the same.
Example:
-It is useful to swap the values of two variables. With conventional assignment statements,
we have to use a temporary variable. For example, to swap a and b:
a=2;b=3
print(a,b)
temp = a
a=b
b = temp
print(a,b)
Output:
(2, 3)
(3, 2)
>>>
In tuple packing, the values on the left are ‘packed’ together in a tuple:
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names
on the right:
>>> name
'George'
>>> age
25
>>> salary
'20000'
Example:
>>> mailid='[email protected]'
>>> name,domain=mailid.split('@')
god
print (domain)
abc.org
This is a preferred approach when you need to return just two or three fields from a function.
The following example shows how you can use tuples to return two fields of different types
from a function.
a=10; b=10
return a,b
>>> x=function()
>>> type(x)
<class 'tuple'>
>>> x
(10, 10)
>>> x,y=function()
>>> x,y
(10, 10)
In Python, a tuple written inside another tuple is known as a nested tuple. Let’s consider a
tuple having 7 elements as shown below.
tup = ( 10, 20, 30, 40, 50, 60, (100, 200, 300))
#Python code
tup = ( 10, 20, 30, 40, 50, 60, (100, 200, 300))
Each nested tuple can represent a specific data record. For instance, records of many students
consisting RollNo, Name and Aggregate can be stored in a nested tuple as depicted below.
#Python code to store records
for i in range(len(StdRec)):
print(i+1,'\t',StdRec[i][0],'\t',StdRec[i][1],'\t',StdRec[i][2])
Python tuple count() is an inbuilt method that helps us to calculate the occurrence of one
element present in the tuple and returns the counted number. The count() method searches the
given component of a tuple and returns how many times the item has occurred in it. The
count() function returns the number of times the specified value appears in the tuple.
Syntax
tuple.count(element)
vowels = ('a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o')
# count element 'a'
count = vowels.count('a')
# print count
count = vowels.count('k')
# print count
Output
In the above code, a character appears 2 times, so it returns 2, and k is not in the tuple so, it
returns 0.
Python index() method is used to find the first occurrence of the specified value in the given
input tuple. It raises an exception if the specified value is not found.
Syntax:
tuple.index(value)
Parameter Values
Parameter Description
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
Output:
3
Example 2:
X = a.index("Jerry")
print(X)
Output:
2
tuple1 = (10,6,45,89,90,1,225,76)
# Here, we store the output of the comprehension into a list and then explicitly convert it into
a tuple.Printing tuple2 and its type:
print(tuple2)
print(type(tuple2))
Output:
<class 'tuple'>
Functions can take a variable number of arguments. A parameter name that begins
with * gathers arguments into a tuple. For example, printall takes any number of arguments
and prints them:
def printall(*args):
print args
The gather parameter can have any name you like, but args is conventional. Here’s how the
function works:
The complement of gather is scatter. If you have a sequence of values and you want to pass
it to a function as multiple arguments, you can use the * operator. For example, divmod takes
exactly two arguments; it doesn’t work with a tuple:
>>> t = (7, 3)
>>> divmod(t)
>>> divmod(*t)
(2, 1)
Exercise 1 Many of the built-in functions use variable-length argument tuples. For
example, max and min can take any number of arguments:
>>> max(1,2,3)
>>> sum(1,2,3)
zip() function
Here, you use zip(numbers, letters) to create an iterator that produces tuples of the form (x, y)
The main difference between Python tuples and lists is that the elements of a tuple cannot be
changed once they are assigned; whereas, the elements of a list can be changed.
As tuples and lists are quite similar to each other, they are often used in similar kinds of
situations. Although, a tuple in Python has a bunch of advantages over lists. Following are
some of the main advantages:
• Iteration in a tuple is faster as compared to lists since tuples in Python are immutable.
• Tuples are generally used for different Python Data Types; whereas, lists are used for
similar data types.
• Whenever, we need to make sure that the data remains unchanged and write
protected, Python tuple is the best option.
• Tuples can be used as dictionary keys, because they contain immutable values like
strings, numbers, etc.
• Tuples are fined size in nature i.e. we can’t add/delete elements to/from a tuple.
Sets
A set is an unordered collection data type with no duplicate elements. Sets are iterable
and mutable. The elements appear in an arbitrary order when sets are iterated.
Sets are commonly used for membership testing, removing duplicates entries, and also
for operations such as intersection, union, and set difference.
Sets can be created by calling the built-in set() function with a sequence or another
iterable object.
>>> print(setA)
set()
>>> print(setA)
>>> print(setA)
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7}
>>> # creating a set with a string. The string has some repeated characters.
>>> print(setA)
Even though mutable objects are not stored in a set, set itself is a mutable object. A set
object can be modified by add(), update(), remove() and discard() methods.
>>>Print(s1)
Output
>>>s1.add("Turbogears")
>>>print(s1)
Output
>>>s2={"NumPy", "SciPy","IPython"}
>>>s1.update(s2)
Output
The remove(), pop() and discard() methods drop an item from the set. pop() method
drops a random item whereas remove() and discard() need an item to be dropped as
argument. If not present in the set, remove() method raises KeyError exception.
>>>s1.remove('SciPy')
>>>print(s1)
Output
>>>s1.remove("Kivy")
KeyError: 'Kivy'
>>>s1.pop()
'Flask'
Output:
s1.discard("Flask")
s1
Output
As mentioned earlier, set data type in Python implements set as defined in mathematics.
Various Set operations like union, intersection, difference and symmetric difference can
be performed using Python’s set object.
>>>s1={10,20,30,40,50}
>>>s2=set('abcde')
>>>s3=s1.union(s2)
>>>print(s3)
Output:
{10, 20, 30, 40, 50, 'a', 'b', 'c', 'd', 'e'}
>>>s1={10,20,30,40,50}
>>>s2={0,20,40,60}
>>>s3=s1.intersection(s2)
>>>print(s3)
Output
{20, 40}
>>>s1={10,20,30,40,50}
>>>s2={0,20,40,60}
>>>s3=s1.difference(s2)
>>>print(s3)
Output:
>>>s1={10,20,30,40,50}
>>>s2={0,20,40,60}
>>>s3=s1.symmetric_difference(s2)
>>>print(s3)
Output
>>>s2={20,40}
>>>s1.difference_update(s2)
>>>print(s1)
Output
>>>s1={10,20,30,40,50}
>>>s2={0,20,40,60}
>>>s1.symmetric_difference_update(s2)
>>>print(s1)
Output
>>>s1={10,20,30,40,50}
>>>s2={0,20,40,60}
>>>s1.intersection_update(s2)
>>>print(s1)
Output
{20, 40}
Following methods decide whether a set is a super set, sub set or two are disjoint.
isdisjoint() Return True if two sets have a null intersection.
s1={10,20,30,40,50}
s2={20,40}
s2.issubset(s1)
s1.issuperset(s2)
s1.isdisjoint(s2)
s2.isdisjoint(s1)
Output
True
True
False
False
clear() method drops all items in the set keeping object intact. The del keyword on the
other hand removes object from memory.
s1.clear()
s1
Output
set()
del s2
s2
---------------------------------------------------------------------------
<ipython-input-42-9b4ca538b1cf> in <module>()
1 del s2
----> 2 s2
Dictionaries
The data type dictionary fall under mapping. It is a mapping between a set of keys and a
set of values. The key-value pair is called an item. A key is separated from its value by a
colon(:) and consecutive items are separated by commas. Items in dictionaries are
unordered, so we may not get back the data in the same order in which we had entered
the data initially in the dictionary.
Creating a Dictionary
To create a dictionary, the items entered are separated by commas and enclosed in curly
braces. Each item is a key value pair, separated through colon (:). The keys in the
dictionary must be unique and should be of any immutable data type, i.e., number, string
or tuple. The values can be repeated and can be of any data type.
Example
>>> dict1 = {}
>>> dict1
{}
#built-in function
There are several methods to remove items from the dictionary. Whether we want to
remove the single item or the last inserted item or delete the entire dictionary, we can
choose the method to be used.
Method Description
Return and removes the item with the key and return its value. If
pop(key[,d])
the key is not found, it raises KeyError.
Return and removes the last inserted item from the dictionary. If the
popitem()
dictionary is empty, it raises KeyError.
del key The del keyword will delete the item with the key that is passed
clear() Removes all items from the dictionary. Empty the dictionary
del
Delete the entire dictionary
dict_name
Now, Let’s see how to delete items from a dictionary with an example.
Example
person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50, 'height': 6}
deleted_item = person.popitem()
print(deleted_item) # output ('height', 6)
print(person)
deleted_item = person.pop('telephone')
print(person)
del person['weight']
print(person)
person.clear()
print(person) # {}
Output
('height', 6)
1178
{}
Sort dictionary
The built-in method sorted() will sort the keys in the dictionary and returns a sorted list.
In case we want to sort the values we can first get the values using the values() and then
sort them.
Example
print(sorted(dict1.items()))
print(sorted(dict1))
Nested dictionary
Nested dictionaries are dictionaries that have one or more dictionaries as their members.
It is a collection of many dictionaries in one dictionary.
Example
# Display dictionary
print("person:", person)
print("City:", person['address']['city'])
print("Person details")
if key == 'address':
else:
Output
person: {'name': 'Jessa', 'company': 'Google', 'address': {'state': 'Texas', 'city': 'Houston'}}
City: Houston
Person details
name: Jessa
company: Google
Person Address
state: Texas
city : Houston
Python provides many functions to work on dictionaries. Table lists some of the commonly
used dictionary methods.
Here are the differences present between List and Dictionary in Python:
Creation We can create a list by placing all We can create a dictionary by placing all
the available elements into a [ ] the available elements into a { } in the
and separating them using “,” form of a key:vale. Here, we have to
commas. separate each pair of available key-values
using the “,” commas.
Data Type The indices in the case of a list The keys present in a dictionary can easily
are basically integers that start be of any given data type.
from the value 0.
Mode of We can access the elements in a We can access the elements present in a
Accessing key using indices. dictionary using the key-values.
Order of The entered order of elements is We don’t have any guarantee of
Elements always maintained. maintaining the order of the available
elements.
Introduction
Till now we have been using the procedure oriented technique in which our
program is written using functions or blocks of statements which manipulate data
however another and infect a better style of programming is called object oriented
programming in which data and functions are combined to form a class compared with
other programming languages python has a very short simple way to define and use
classes and objects.
Classes and objects are the two main aspects of object oriented programming. In
fact class is a basic building block in python. class creates a new type and object is an
instance or variable of the class. classes provides a blueprint or a template using which
objects are created. In fact in python everything is an object or an instance of some class.
for example all integer variables that we define in our program actual instance of class
int, similarly all string variables are objects of class string.
Just as a function in Python is defined using the def keyword, a class in Python is also
defined using the class keyword, followed by the class name.
Class <classname>:
Statement1
Statement2
…
Statement_n
the class definition with the class keyword, followed by the class name and a colon(;)
statement in the definition can be any of these-sequential instructions. decision control
statements, loop statements and can even include function definitions. Variables defined
in a class are called class variables and functions defined inside a class are called class
methods.class variables and class methods are together called as class members. Class
members are accessed through class objects
Creating an Object
The object is created after creating a class. Instant of the object is created using the name
same as the class name and it is known as class Instantiation. One can give any name to
a newly created object. Object creation is similar to calling a function. This is because as
soon as the object is created or instantiated with the class name, the default constructor
of the class is called automatically.
Syntax
#object instantiation
object_name = class_name()
Class ABC:
Obj=ABC()
Output
10
In above program a class ABC which has a variable var having a value of 10. The object
of the class is created and used to access the class variable using the dot operator.
Abstraction is used to hide the internal functionality of the function from the
users. The users only interact with the basic implementation of the function, but inner
working is hidden. User is familiar with that "what function does" but they don't know
"how it does. In simple words, we all use the smartphone and very much familiar with
its functions such as camera, voice-recorder, call-dialing, etc., but we don't know how
these operations are happening in the background. Let's take another example - When
we use the TV remote to increase the volume. We don't know how pressing a key
increases the volume of the TV. We only know to press the "+" button to increase the
volume.In Python, an abstraction is used to hide the irrelevant data/class in order to
reduce the complexity. It also enhances the application efficiency.
Encapsulation is the packing of data and functions that work on that data within a
single object. By doing so, you can hide the internal state of the object from the outside.
This is known as information hiding. A class is an example of encapsulation. A class
bundles data and methods into a single unit. And a class provides the access to its
attributes via methods. The idea of information hiding is that if you have an attribute that
isn’t visible to the outside, you can control the access to its value to make sure your
object is always has a valid state.
Public data members are accessible within and outside of a class. All member
variables of the class are by default public. We can protect variables in the class by
marking them private. To define a private variable add two underscores as a prefix at the
start of a variable name. Private members are accessible only within the class, and we
can’t access them directly from the class objects.
When we create a class in Python, instance methods are used regularly. To work with an
instance method, we use the self keyword. We use the self keyword as the first
parameter to a method. The self refers to the current object. Any method we create in a
class will automatically be created as an instance method unless we explicitly tell
Python that it is a class or static method. Instance variables are not shared between
objects. Instead, every object has its copy of the instance attribute. Using the instance
method, we can access or modify the calling object’s attributes.
Instance methods are defined inside a class, and it is pretty similar to defining a
regular function.
You may use a variable named differently for self, but it is discouraged since self is the
recommended convention in Python. We use an object and dot (.) operator to execute the
block of code or action defined in the instance method.
• First, create instance variables name and age in the Student class.
• Next, create an instance method display() to print student name and age.
• Next, create object of a Student class to call the instance method.
Program to access class members using the class object
Class ABC():
Var=10
Def display(self):
Obj=ABC()
Print(obj.var)
Obj.display()
Output
10
In class method
Python class constructor function job is to initialize the instance of the class. Python
__init__() is the constructor function for the classes in Python. The __init__() function
syntax is:
# class
class Awesome:
def __init__(self):
self.greetings()
# methods
def greetings(self):
obj = Awesome()
The data part, i.e. fields, are nothing but ordinary variables that are bound to
the namespaces of the classes and objects. This means that these names are valid within
the context of these classes and objects only. That’s why they are called name spaces.
There are two types of fields – class variables and object variables which are classified
depending on whether the class or the object owns the variables respectively.
Class variables are shared – they can be accessed by all instances of that class. There is
only one copy of the class variable and when any one object makes a change to a class
variable, that change will be seen by all the other instances.
Object variables are owned by each individual object/instance of the class. In this case,
each object has its own copy of the field i.e. they are not shared and are not related in
any way to the field by the same name in a different instance.
class Car:
# Class variable
manufacturer = 'BMW'
# instance variable
self.model = model
self.price = price
# create Object
Output:
x1 2500 BMW
Understanding the difference between the Class Variable and Instance Variable
Since we have understood the basic concepts of both the variables and how these
variables are used in the class, let us understand how class variable differs from
the instance variable. The major differences between these two variables are
described in the tabular format shown below:
S. Class Variable Instance Variable
No.
6 It has only one replica of the class It has multiple replicas, so each
variable, so it is shared between object has its replica of the
various class objects. instance variable.
In Python, destructor is not called manually but completely automatic. destructor gets
called in the following two cases
In Python, The special method __del__() is used to define a destructor. For example,
when we execute del object_name destructor gets called automatically and the object
gets garbage collected.
The magic method __del__() is used as the destructor in Python. The __del__() method
will be implicitly invoked when all references to the object have been deleted, i.e., is
when an object is eligible for the garbage collector.
def __del__(self):
# body of a destructor
Where,
Note: The __del__() method arguments are optional. We can define a destructor with
any number of arguments.
class Student:
# constructor
print('Inside Constructor')
self.name = name
print('Object initialized')
def show(self):
# destructor
def __del__(self):
print('Inside destructor')
print('Object destroyed')
# create object
s1 = Student('Emma')
s1.show()
# delete object
del s1
Output
Inside Constructor
Object initialized
Inside destructor
Object destroyed
The variables which are defined inside the class is public by default. These variables can
be accessed anywhere in the program using dot operator.
A variable prefixed with double underscore becomes private in nature. These variables
can be accessed only within the class.
class Sample:
self.n1=n1
self.__n2=n2
def display(self):
S.display()
In the above program, there are two class variables n1 and n2 are declared. The variable
n1 is a public variable and n2 is a private variable. The display( ) member method is
defined to show the values passed to these two variables.
The print statements defined within class will successfully display the values of n1 and
n2, even though the class variable n2 is private. Because, in this case, n2 is called by a
method defined inside the class. But, when we try to access the value of n2 from outside
the class Python throws an error. Because, private variable cannot be accessed from
outside the class.
Output
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12
Private methods
Private methods are such methods that cannot be accessed outside a class definition. In
the real world, if something is private to us, other people aren’t supposed to have access
to that. Similarly, We are not supposed to access the private methods defined inside a
class.
Python doesn’t support private methods. But, we can simulate the implementation of
private methods in python. For that, we have to define the name of the private method
using two underscore signs as follows.
def __methodName():
pass
Here, we have used the def keyword to define the method and the pass keyword has
been used to create a method body that does nothing.
# Creating a class
class A:
def fun(self):
print("Public method")
def __fun(self):
print("Private method")
# Driver's code
obj = A()
obj._A__fun()
Output:
Private method
we can call the method of another class by using their class name and function with dot
operator.
for Example:-
if the 1st class name is class A and its method is method_A
and the second class is class B and its method is method_B
A stack data structure is used during the execution of the function calls. Whenever a
function is invoked then the calling function is pushed into the stack and called function
is executed. When the called function completes its execution and returns then the
calling function is popped from the stack and executed. Calling Function execution will
be completed only when called Function is execution completes.
def Square(X):
return (X * X)
Sum = 0
for i in range(n):
SquaredValue = Square(Array[i])
Sum += SquaredValue
return Sum
# Driver Function
n = len(Array)
Total = SumofSquares(Array, n)
Output :
Sum of the Square of List of Numbers: 385
Attributes of a class are function objects that define corresponding methods of its
instances. They are used to implement access controls of the classes.
Attributes of a class can also be accessed using the following built-in methods and
functions :
The following methods are explained with the example given below :
class emp:
name='Harsh'
salary='25000'
def show(self):
print (self.name)
print (self.salary)
e1 = emp()
print (hasattr(e1,'name'))
# sets an attribute
setattr(e1,'height',152)
print (getattr(e1,'height'))
delattr(emp,'salary')
Output :
Harsh
True
152
Every Python class keeps following built-in attributes and they can be accessed using
dot operator like any other attribute −
For the above class let us try to access all these attributes −
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
Employee.__module__: __main__
Employee.__bases__: ()
Garbage Collection
Python deletes unneeded objects (built-in types or class instances) automatically to free
the memory space. The process by which Python periodically reclaims blocks of
memory that no longer are in use is termed Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an
object's reference count reaches zero. An object's reference count changes as the number
of aliases that point to it changes.
You normally will not notice when the garbage collector destroys an orphaned instance
and reclaims its space. But a class can implement the special method __del__(), called a
destructor, that is invoked when the instance is about to be destroyed. This method
might be used to clean up any non memory resources used by an instance.
Class Method
class C(object):
@classmethod
....
• A class method is a method that is bound to the class and not the object of the
class.
• They have the access to the state of the class as it takes a class parameter that
points to the class and not the object instance.
• It can modify a class state that would apply across all the instances of the class.
For example, it can modify a class variable that will be applicable to all the
instances.
Static Method
Syntax:
class C(object):
@staticmethod
...
• A static method is also a method that is bound to the class and not the object of
the class.
• A static method can’t access or modify the class state.
• It is present in a class because it makes sense for the method to be present in
class.
• A class method takes cls as the first parameter while a static method needs no
specific parameters.
• A class method can access or modify the class state while a static method can’t
access or modify it.
• In general, static methods know nothing about the class state. They are utility-
type methods that take some parameters and work upon those parameters. On the
other hand class methods must have class as a parameter.
• We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.
The __init__() Function
The examples above are classes and objects in their simplest form, and are not really
useful in real life applications.
All classes have a function called __init__(), which is always executed when the class is
being initiated.
Use the __init__() function to assign values to object properties, or other operations that
are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and
age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used
to create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Note: The self-parameter is a reference to the current instance of the class, and is used to
access variables that belong to the class.
The self-Parameter
The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:
Example
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()