0% found this document useful (0 votes)
16 views23 pages

Unit 3

Uploaded by

Keerthana K S
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)
16 views23 pages

Unit 3

Uploaded by

Keerthana K S
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/ 23

UNIT 3

Object oriented programming:


Classes and objects:

• A class is a blueprint from which individual objects are created.


• An object is a bundle of related state (variables) and behavior (methods).
Creating classes and objects:

• Classes are defined by using the class keyword, followed by the ClassName and a
colon.
class ClassName:
<statement-1>
-
<statement-N>
the statements inside a class definition will usually be function definitions. Because these
functions are indented under a class, they are called methods. Methods are a special kind of
function that is defined within a class.
Ex:
Class student:
Name:’abc’
Branch:’cs’
Def read(self):
Print(“read the data”)
Def write(self):
Print(“accessing”)
Creating objects:

• Object refers to a particular instance of a class where the object contains variables and
methods defined in the class.
• Class objects support two kinds of operations: attribute references and instantiation. The
term attribute refers to any name (variables or methods) following a dot.
• The act of creating an object from a class is called instantiation.
Syntax:
object_name = ClassName(argument_1, argument_2, ....., argument_n)
• Variables defined within the class are called instance variables and are used to store data
values.
• New instance variables are associated with each of the objects that are created for a
class. These instance variables are also called data attributes.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 1


The syntax to access data attribute is,
object_name.data_attribute_name

The syntax to assign value to data attribute is,


object_name.date_attribute_name = value
ex:
Class student:
Name:’abc’
Branch:’cs’
Def read(self):
Print(“read the data”)
Def write(self):
Print(“accessing”)
ab=student()
here ab is the object for class student, which is used for accessing variables and methods.
ab.name
ab.branch
ab.read()
ab.write()
Constructor method:

• Python uses a special method called a constructor method. It is invoked as soon as an


object of a class is instantiated denoted as The __init__().
• The __init__() method for a newly created object is automatically executed with all of
its parameters.
Syntax:
def __init__(self, parameter_1, parameter_2, ...., parameter_n):
statement(s)

• The parameters for __init__() method are initialized with the arguments that you had
passed during instantiation of the class object.
• The number of arguments during the instantiation of the class object should be
equivalent to the number of parameters in __init__() method(excluding the self
parameter).
Note: The first parameter in each of methods is the word self. When self is used, it is just a
variable name to which the object that was created based on a class is assigned.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 2


Classes with multiple objects:
Multiple objects for a class can be created while attaching a unique copy of data attributes
and methods of the class to each of these objects.
Ex: Class student:
Name:’abc’
Branch:’cs’
Def read(self):
Print(“read the data”)
Def write(self):
Print(“accessing”)
S1=student()
S2=student()
Here class student has multiple objects s1 and s2.
Objects as arguments:

• An object can be passed to a calling function as an argument.


• Objects as return values: In Python, “everything is an object” (that is, all values are
objects) because Python does not include any primitive values.
• The id() function is used to find the identity of the location of the object in memory.
syntax for id() function is,
id(object)
This function returns the “identity” of an object.

• Can also check whether an object is an instance of a given class or not by using the
isinstance() function.
The syntax for isinstance() function is,
isinstance (object, classinfo)
The isinstance() function returns a Boolean stating whether the object is an instance or
subclass of another object.

Inheritance

• Inheritance is a way to express a relationship between classes. Inheritance enables new


classes to receive or inherit variables and methods of existing classes.
• A class that is used as the basis for inheritance is called a superclass, parent class or
base class.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 3


• A class that inherits from a base class is called a subclass, child class or derived class
respectively. A derived class inherits variables and methods from its base class while
adding additional variables and methods of its own.
To create a derived class, pass the Base Class Name after the DerivedClassName within the
parenthesis followed by a colon.
Syntax:
class DerivedClassName(BaseClassName):
<statement-1>
.
<statement-N>

• Variables and methods are accessed by creating an object in the derived class. Inherited
variables and methods are also accessed just as if they had been created in the derived
class itself.
Single inheritance

• It enables a derived class to inherit variables and methods from a single base class.
• Object is created in the derived class for accessing both variables and methods.
Example:
Class parent
Def display(self):
Print(“parent class”)
Class child(parent)
Def cdisplay(self):
Print(“child class”)
c=child()
c.display()
c.cdisplay()

• C is the object created in derived class i.e. child, which is used to access variables and
methods of both child class and parent class.
Multilevel inheritance: In multilevel inheritance features of the base class and the derived
class are further inherited into the new derived class.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 4


a
a-base class

b b-intermediatory class
c-derived class
c

class base:
def display(self):
print (“base class”)
class intermediatory(base):
def idisplay(self):
print (“intermediatory class”)
class derived(intermediatory):
def ddisplay(self):
print (“derived class”)
d=derived ()
d.ddisplay()
d.idisplay()
d.display()
Multiple inheritance: Derived class is inherited from multiple base classes,
class DerivedClassName(Base_1, Base_2, Base_3):
<statement-1>
<statement-N>
Ex:
Class base1:
def b1display(self):
Print(“display base class)
Class base2:
def b2display(self):
Print(“display b2 base class”)
Class derived(base1,base2):

POOJITHA G S, ASST. PROFESSOR, NIE FGC 5


def show(self):
print(“display derived class”)
d=derived()
d.b1display()
d.b2display()
d.show()
Multipath inheritance:

• when a class is derived from two or more classes which are derived from the same base
class.
• It includes other types of inheritance such as multiple, hierarchical, multilevel.

Class A:
def adisplay(self):
Print(“base class”)
Class B(A):
def bdisplay(self):
Print(“ class B”)
Class C(A):
def cdisplay(self):
Print(“class C”)
Class D(B,C):
def ddisplay(self):
Print(“class D”)
d=D()
d.display()
d.cdisplay()
d.bdisplay()
Encapsulation: Encapsulation is the process of combining variables that store data and
methods that work on those variables into a single unit called class.

• In Encapsulation, the variables are not accessed directly; it is accessed through the
methods present in the class.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 6


• Encapsulation ensures that the object’s internal representation (its state and behavior) is
hidden from the rest of the application.
• Encapsulation is achieved by restricting the scope of variables and methods.
Data/method can be accessed within the class.
Note:
By default, accessibility is public.to make it private double underscore is prefixed for variable
and method name.
Example:
Class A:
a=10
Def display(self):
Print (“class A”)
Here variable and method are public. This can be made private
Class A:
__a=10
Def __display(self):
Print (“class A”)
Private instance variable:

• Variables called inside a class is called instance variable.


• It can be used only within the class it is called.
• Private is indicated by prefixing the variable and method with double underscore(__)
Ex:
Class student:
__Name:’abc’ private instance variables
__Branch:’cs’
Def read(self):
Print(“read the data”)
Def write(self):
Print(“accessing”)

Polymorphism:

• if something exhibits various forms, it is called as polymorphism.


• A variable can store different types of data, an object can exhibit different behavior.
• Polymorphism can be achieved in 2 ways

POOJITHA G S, ASST. PROFESSOR, NIE FGC 7


Overloading
Overriding
Overloading:
Operator overloading
Method overloading
Operator overloading:
Single operator performing differently depending on type of data.
Ex:
Operator +
If it’s given with integer sumup the numbers.
If it’s given with strings then concatenates 2 strings.

Method overloading:
Function name is same but the number of arguments are different.

GU interface:
The tkinter module:

• The easiest and fastest way to create GUI is using python with tkinter. It provides
different tools to work with graphics. TK stands for tool kit.
• Tkinter allows to work with the classes of TK module of tool command language (TCL)
which is best for web and desktop applications.
• TK provides standard GUI, which can be used by dynamic programming languages
such as python.
To create a tkinter app:
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.

The first step involves importing tkinter.


from tkinter import*

Create the main window:


Windows are the containers in which all other GUI elements live.
window=tkinter.Tk()
where window is the name of the main window object

mainloop():
• mainloop() is used when application is ready to run.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 8


• It is an infinite loop, wait for an event to occur and process the event as long as the
window is not closed.
Syntax:
window.mainloop()
ex:
from tkinter import*
window=Tk()
window.mainloop()

Title:this method is used to set title of the window.


window=title(“ title”)
example:
window.title("welcome")

Geometry: this method is used to change the size of the window.


window. Geometry(“size”)
example:
window. Geometry("400x600")

widgets:
widgets are the elements through which users interact with the program. Each widget in
Tkinter is defined by a class.
Some important widgets are:
Buttons, label, checkbutton, listbox, canvas, menu, frame etc.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 9


1)Button: To add a button in your application, this widget is used.
The general syntax is:
Button name=Button (master, option=value)
• master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number
of options can be passed as parameters separated by commas.
• Active background(bg): to set the background color
• Active foreground(fg): to set the foreground color
• command: to call a function.
• font: to set the font on the button label.
Example:
button=Button(window,text='click here',fg='red',command=messaage)

2)label: Label widgets are used to display text or images.


Label name=Label (master, option=value)
• master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the . Number of
options can be passed as parameters separated by commas.
• bg: to set the normal background colour.
• command: to call a function.
• font: to set the font on the button label.

Example:
label=Label(window,text='NIEFGC',fg='red',bg='white').pack()

3) CheckButton: To select any number of options by displaying a number of options to a


user as toggle buttons. The general syntax is:
w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• Title: To set the title of the widget.
• foreground: to set the foreground color
• background: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the widget.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 10


Layout management:
• Layout managers are used to place widgets on to the parent window.
• Their task is to arrange the position of the widget on the screen.
There are 3 layout mangers
1)pack
2)grid
3)place

1)pack: The pack geometry manager organizes widgets in horizontal and vertical boxes. The
layout is controlled with the
• Fill-to make the widgets as wide as the parent widget, use the fill=X option.
Ex: button=Button(window,text='click here',fg='red',command=messaage).pack(fill=’x’)

• Expand-it has two values true or false


button=Button(window,text='click here',fg='red',command=messaage).pack(expand=true)

• Side-decides which side of the parent window the widget appears. The values are top,
bottom, left, right.

Example:
button=Button(window,text='click here',fg='red',command=messaage).pack(side=’left’)

POOJITHA G S, ASST. PROFESSOR, NIE FGC 11


2)grid: this method is used to organize the widgets in a table like structure.
Methods used in grid layout are:
• Column and row: determine the position of the widgets.
• Columnspan: number of columns occupied. Default value is 1.
• Rowspan: number of rows occupied. Default value is 1.
• Sticky: how widget stick to the cell.
• Padding: ipadx, ipady, padx, pady-adjusting the borders.
3)place: this method allows to place widgets in a window in an absolute or relative position.

Python SQLite
Sqlite3 module:
• SQLite is a server-less database that can be used within almost all programming
languages including Python.
• Python has a library to access sqlite database called sqlite3.
• Server-less means there is no need to install a separate server to work with SQLite, can
be connected directly with the database.
• SQLite is a lightweight database that can provide a relational database management
system with zero-configuration as there is no need to set up anything to use it.
SQLite method:
Connect:
• connecting to the sqlite database can be established using connect method.
• database name is passed as argument.
• create a connection object which will connect us to the database.
Syntax:
Sqliteconnection=sqlite3.connect(“database name”)

Example:
import sqlite3
con=sqlite3.connect("bca.db")

Cursor:
• to execute queries after connection a cursor ha to be created using cursor method.
• It is an object that is used to make the connection for executing sql queries.
• It acts as middleware between SQLite database connection and sql query.
Syntax:
Cursor object=sqliteconnection. cursor ()

POOJITHA G S, ASST. PROFESSOR, NIE FGC 12


Execute: the sql query to be executed can be written in the form of string.
Query is executed by calling execute method on cursor object.
Syntax:
Cursor.execute(query)

Close: To close a connection, use the connection object and call the close() method
Syntax:
Cursor object.close()
Connect to database:
• When you create a connection with SQLite, that will create a database file
automatically if it doesn’t already exist.
• This database file is created on disk; we can also create a database in RAM by using
: memory: with the connect function. This database is called in-memory database.

con = sqlite3.connect(':memory:')

Create table:

To create a table in SQLite3, you can use the Create Table query in the execute() method.
Consider the following steps:

1. Create a connection object.


2. From the connection object, create a cursor object.
3. Using the cursor object, call the execute method with create table query as the
parameter.

Syntax:

Cursor Object.execute("CREATE TABLE tablename (column1 text, column2 integer,

column3 text”)

Example:

c.execute("""create table student(


name text,
id int,

POOJITHA G S, ASST. PROFESSOR, NIE FGC 13


course text
)""")

Operations on tables:
Insert: To insert data in a table, use the INSERT INTO statement.
Syntax: cursor object. execute (insert into tablename values (val 1, val 2, val n))
Example:
c.execute("insert into student values('p',1,'bca')")

Select:
• select statement is used to retrieve data from a sqlite table and this returns the data
contained in the table.
• Select * from tablename;
* Retrieves all the column from the table.
Replace * with column name from specific data.
Syntax:
Cursor object. execute (“select * from table name”)
Example:
c.execute("insert into student values('p',1,'bca')")

Update: update statement is used to update the data of a existing table.


Syntax:
Cursor object. execute (“update student set column=value where condition”)
Example:
c.execute("update student set course='bca' where id=2")

Delete: delete statement is passed as parameter to execute method.


Syntax:
Cursor object.execute(“Delete from tablename where clause”)
Example:
c.execute ("delete from student where id=2")

Drop: used to drop\delete entire database.


Syntax:

POOJITHA G S, ASST. PROFESSOR, NIE FGC 14


Cursor object. execute (‘Drop table tablename’)

Data analysis:
Numpy:
NumPy is the fundamental package for scientific computing with Python. It stands for
“Numerical Python.”
It supports:
• N-dimensional array object
• Broadcasting functions
• Useful for linear algebra, Fourier transform, and random number capabilities.
In NumPy arrays, the individual data items are called elements. All elements of an array
should be of the same type.
Array creation:
• a NumPy array is created by using the np.array() function, where list or tuple is
passed as parameter.

import numpy as np
array=np.array([1,2,3])
• Pass a list of items to the np.array() function and assign the result to array object.
• 2d arrays are created by passing the items separated by comma.
Example:
Array1=np.array([1,2,3],[4,5,6])
Here array1 is 2d array
Ndim() function gives the array dimension
Print(array.ndim)
Shape(): it provides the number of shape (rows and columns) of an array.
Print(array.shape)

Operations on arrays:
1)accessing :retrieves particular element from an array.
Syntax:
Array name[index]
Example:
B=np.array([1,2,3])
B[2]
Output:
3

POOJITHA G S, ASST. PROFESSOR, NIE FGC 15


2)slicing:retrieves part of an array where,
[start index:stop index:step size]
Where,
Start index is 0 by default
Stop index is length of the array by default
Step size is 1 by default
[::] gives all the array elements.
Example:
A=np.array([1,2,3,4,5,6])
A[1::]
Here only start index is provided all other values are default values.hence stop index is
length of array and step size is 1.
Output:
2
3)basic arithmetic operations:
Rules for implementing arithmetic operations:
1)shape of two arrays must be equal
2)if second array is 1 dimension then number of elements should be equal to the first array.
Example:
b=np.array([[1,2,3],[4,5,6]])
c=np.array([1,2,3])
addition:
syntax:np.add(array1,array2)
ex:np.add(b,c)
here as second array is 1d, its number of elements should match the first array.
[[2 4 6]
[5 7 9]]

Subtraction:
Syntax: np.subtract(array1,array2)
Ex:
np. subtract(b, c)
subtraction of 2 arrays
[[0 0 0]

POOJITHA G S, ASST. PROFESSOR, NIE FGC 16


[3 3 3]]

multiplication:
syntax: np.multiply(array1,array2)
ex:
np.multiply(b,c)
multiplication of 2 arrays
[[ 1 4 9]
[ 4 10 18]]

division:
syntax: np.divide(array1,array2)
ex
:np.divide(b,c)
division of 2 arrays
[[1. 1. 1.]
[4. 2.5 2.]]

modulus:np.mod(b,c)
modulus of 2 arrays
[[0 0 0]
[0 1 0]]

Pandas:
• pandas is a Python library that provides fast, flexible, and expressive data structures.
• The two primary data structures of pandas, Series (one-dimensional) and
DataFrame(two-dimensional).
• Import pandas as,
import pandas as pd
Series:
Series is a one-dimensional labelled array capable of holding any data type (integers,
strings,
floating point numbers, Python objects, etc.)
syntax,
s = pd. Series (data, index=None)

POOJITHA G S, ASST. PROFESSOR, NIE FGC 17


Here, s is the Pandas Series, data can be a Python dict, a ndarray. The passed index is a list of
axis labels.
DataFrames:
• DataFrame is a two-dimensional, labelled data structure with columns.
• DataFrame accepts many different kinds of input like Dict of one-dimensional
ndarrays, lists, dictionaries, or Series.
Syntax:
df = pd.DataFrame (data, index=None, columns=None)
here its optional to pass index and columns.
Create DataFrames from excel sheet:
• DataFrames from excel are created using read_excel method along with passing the
complete path of excel file.
Syntax:
df=pd.read_excel(“path”)
ex:
df=pandas. read_excel ("C:\\Users\Desktop\excelpy.xlsx ")
print(df)

Create DataFrames from .csv file:

• Csv is comma separated files.

• DataFrames from .csv file are created using read_csv method along with passing the
complete path as parameter.
Syntax:
df=pandas. read_csv(“path”)
ex:
df1=pandas.read_csv ("C:\\Users\Desktop\excel1py.xlsx ")

Create DataFrames from dictionary:


Here dictionary is passed as parameter to the DataFrame.
Syntax:
df=pandas.DataFrame(dictionary name)
Ex:d={'name':['a','ab','abc'],'course':['bca','bsc','bca'],’sub’:[‘py’,’cn’,’c’]}
df=pandas.DataFrame(d)

Name course sub


0 a bca py
1 ab bsc cn

POOJITHA G S, ASST. PROFESSOR, NIE FGC 18


2 ab c bca c
Here the dictionary is converted into rows and columns when into DataFrames and its also
indexed.
Create DataFrames from tuple:

• pass a tuple as an argument to DataFrame.


• DataFrame indexes it.
Ex:
tuple=[(‘name’,‘a’,’BCA’)]
df=pandas.DataFrame(tuple)
output:
0 name a BCA
Operations on DataFrames:
Example:
Name course sub
0 a bca py
1 ab bsc cn
2 ab c bca c

1)Head: retrieves the topmost rows.


Syntax: DataFrame name.head()
Ex:df.head(2)
It retrieves top 2 rows.
2)tail: retrieves the last elements.
Syntax:
DataFrame name.tail()
Ex:
df.tail(1)
Retrieves the last row.
3)loc-retrieves particular row
Syntax:DataFrame name.loc[]
Ex:df.loc[1]
4)access particular data(filter):

POOJITHA G S, ASST. PROFESSOR, NIE FGC 19


df[df[‘name’]==’a’]
it retrieves the data which as name =a.
5)add column:
Dictionary name [‘column name’] = [value1, value2….]
Ex:
df[‘grade’] =[‘A’,’B’,’C’]
Print(df)
Output:
Name course sub grade
0 a bca py A
1 ab bsc cn B
2 ab c bca c C

Data visualization:
Introduction:

• Presentation of data in pictorial or graphical formats is known as data visualization.


• data visualization helps in understanding the trends well and take better decisions.
• It helps in faster action as graphs and charts are able to summarize complex data very
efficiently.
Matplotlib library:
Matplotlib is python’s library for generating high quality 2D graphics such as charts, figures
and graphs (bar, histogram plots).
It provides variety of plots to understand patterns and trends.
Matplotlib consists of interfaces such as pyplot and pylab, wherein most of the utilities are
under myplot submodule.
Import matplotlib. pyplot as plt
Figure:place where chart are created.
Axes:drawings represented on the figure.each axes is divided into x,y and z axis.
Legend: it provides formula functionality.
Different charts using pyplot
1)line chart:

• Plot() function is used for plotting wherein the x and y axis are passed as parameters.

POOJITHA G S, ASST. PROFESSOR, NIE FGC 20


• x stands for value of x-axis and y stands for value of y axis.
Plt.plot(x,y)

• Show() function is used for displaying the plot.


Plt.show()

• Fuctions xlabel,ylabel are used for labelling x and y axis.


• Title function is used to provide a title to the plot.
Ex:
import matplotlib.pyplot as plt
x=['a','b','c','d']
y=[50,60,70,80]
plt.plot(x,y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

2)Bar chart: data is represented in the form of vertical or horizontal bars.


It is useful for comparing the quantities.
Horizontal bars: these are created by using barh() function and height of the bars are to be
mentioned.
Plt.barh(x,y,height=0.7)
Where the height is 0.8 by default
Vertical bars: these are created by using bar function and width of the bars are to be
mentioned.
Plt.barh(x,y,width=0.7)
Where the width is 0.8 by default

Ex:

POOJITHA G S, ASST. PROFESSOR, NIE FGC 21


import matplotlib.pyplot as plt
a=['a','b','c','d']
b=[20,25,30,40]
c=['red','green','yellow','blue']
plt.bar(a,b,color=c,width=0.7)
plt.title(" bar chart")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

3)histogram: histogram shows values grouped in intervals.


To draw histogram hist () function is used
Plt.hist()
The arguments passed are
1.the values
2.histtype: provides how histogram should be displayed. The types are-bar,step,stepfilled.
3)width of the bars.
Ex:
from matplotlib import pyplot as plt
marks=[25,40,50,70,80]
grade=[0,30,60,70,90]
plt.xlabel("marks")
plt.ylabel("grade")
plt.hist(marks,grade,histtype="bar")
plt.show()

POOJITHA G S, ASST. PROFESSOR, NIE FGC 22


4)pie chart: a pie chart shows a circle that is divided into sectors and each sector represents a
proportion of the whole data.
To create a pie chart pie () function is used.
Plt.pie()
Parameters passed are:
1)values of y axis
2)values of x axis is assigned to label.
3)explode: indicates whether the slice should be dragged out or not. All slice values are 0 by
default
4)autopct:to display the percentage on the slices.
5)color: provides color for each slice.

• Legend is created by using legend () function


plt.legend()
Ex:
from matplotlib import pyplot as plt
student_performance=["excellent","good","average","poor"]
students count=[12,20,10,5]
plt.pie(students_count,labels=student_performance,colors=['red','green','yellow','blue'],autopc
t="%2.1f%%",explode=[0.2,0,0,0])
plt.legend()
plt.show()

POOJITHA G S, ASST. PROFESSOR, NIE FGC 23

You might also like