Unit 3
Unit 3
• 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.
• 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.
• 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
• 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.
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):
• 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.
Polymorphism:
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.
mainloop():
• mainloop() is used when application is ready to run.
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.
Example:
label=Label(window,text='NIEFGC',fg='red',bg='white').pack()
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’)
• 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’)
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 ()
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:
Syntax:
column3 text”)
Example:
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')")
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
Subtraction:
Syntax: np.subtract(array1,array2)
Ex:
np. subtract(b, c)
subtraction of 2 arrays
[[0 0 0]
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)
• 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 ")
Data visualization:
Introduction:
• Plot() function is used for plotting wherein the x and y axis are passed as parameters.
Ex: