Professional Documents
Culture Documents
CO1 Python OOPs Concepts
CO1 Python OOPs Concepts
An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-world entities such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve the problem by creating objects.
• Class
• Object
• Method
• Inheritance
• Polymorphism
• Data Abstraction
• Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the function
source code.
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.
1
Example:
class student:
def __init__(self,studname, regno):
self.studentname = studname
self.regno = regno
def display(self):
print(self.studname,self.regno)
s1 = student("Ram", 1908)
s1.display()
Output:
Ram 1908
In the above example, we have created the class named student, and it has two attributes
studname and regno. We have created a s1 object to access the class attribute. The 11 object will
allocate memory for these values.
Method
The method is a function that is associated with an object. In Python, a method is not unique to
class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the
real-world concept of inheritance. It specifies that the child object acquires all the properties and
behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of another
class. The new class is known as a derived class or child class, and the one whose properties are
acquired is known as a base class or parent class.
2
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means
shape. By polymorphism, we understand that one task can be performed in different ways. For
example - you have a class animal, and all animals speak. But they speak differently. Here, the
"speak" behavior is polymorphic in a sense and depends on the animal. So, the abstract "animal"
concept does not actually "speak", but specific animals (like dogs and cats) have a concrete
implementation of the action "speak".
Encapsulation
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms
because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something
means to give names to things so that the name captures the core of what a function or a whole
program does.
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.
On the other hand, the object is the instance of a class. The process of creating an object can be
called instantiation.
In Python, a class can be created by using the keyword class, followed by the class name. The
syntax to create a class is given below.
Syntax
class ClassName:
#statement_suite
In Python, 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.
3
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display(), which is used to display the information of
the Employee.
Example
class Employee:
id = 10
name = "John"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It is always
the first argument in the function definition. However, using self is optional in the function call.
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.
A class needs to be instantiated if we want to use the class attributes in another class or method.
A class can be instantiated by calling the class using the class name.
<object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above example.
Example
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
4
emp.display()
Output:
ID: 10
Name: John
In the above code, we have created the Employee class which has two attributes named id and
name and assigned value to them. We can observe we have passed the self as parameter in
display function. It is used to refer to the same class attribute.
We have created a new instance object named emp. By using it, we can access the attributes of
the class.
We can delete the properties of the object or object itself by using the del keyword. Consider the
following example.
Example
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating a emp instance of Employee class
emp = Employee()
# Deleting the property of object
del emp.id
# Deleting the object itself
del emp
emp.display()
It will through the Attribute error because we have deleted the object emp.
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.
5
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.
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.
Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
emp1.display()
# accessing display() method to print employee 2 information
emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
6
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.
Example
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
Output:
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.
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
The parameterized constructor has multiple parameters along with the self. Consider the
following example.
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
7
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Output:
Hello John
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.
Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
Output:
101 Joseph
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
8
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Smith")
x.printname()
Output:
John Smith
To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods from
the Person class:
class Student(Person):
pass
9
Note: Use the pass keyword when you do not want to add any other properties or methods to the
class.
Now the Student class has the same properties and methods as the Person class.
Example
Use the Student class to create an object, and then execute the printname method:
x = Student("Srinvasa", "Rao")
x.printname()
Output:-
Srinivasa Rao
We have created a child class that inherits the properties and methods from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to create
a new object.
Example
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
10
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Srinivasa", "Rao")
x.printname()
Output:
Srinivasa Rao
Now we have successfully added the __init__() function, and kept the inheritance of the parent
class, and we are ready to add functionality in the __init__() function.
Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("John", "Smith")
11
x.printname()
Output :
John Smith
By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.
2. Collections
Python Lists
mylist = ["apple", "banana", "cherry"]
List
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Example
Create a List:
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the
items will not change.
12
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Example
Example
13
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
It is also possible to use the list() constructor when creating a new list.
Example
There are four collection data types in the Python programming language:
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security
Access Items
List items are indexed and you can access them by referring to the index number:
Example
Example
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
Specify negative indexes if you want to start the search from the end of the list:
15
Example
This example returns the items from "orange" (-4) to, but NOT included. "mango" (-1):
Example
Example
16
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
17
remove() Removes the item with the specified value
Python Tuples
Tuple
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
Example
Create a Tuple:
Tuple Items
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.
18
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
has been created.
Allow Duplicates
Since tuple are indexed, tuples can have items with the same value:
Example
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
To create a tuple with only one item, you have to add a comma after the item, otherwise Python
will not recognize it as a tuple.
Example
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
19
Tuple Items - Data Types
Example
Example
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
Example
20
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
Set
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
Example
Create a Set:
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
21
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.
Unchangeable
Sets are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can add new items.
Example
print(thisset)
To determine how many items a set has, use the len() method.
Example
print(len(thisset))
Example
22
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
Example
type()
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Example
Example
Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and does not allow duplicates.
23
Dictionaries are written with curly brackets, and have keys and values:
Example
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are unordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Example
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Unordered
When we say that dictionaries are unordered, it means that the items does not have a defined
order, you cannot refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
24
Duplicates Not Allowed
Example
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
print(len(thisdict))
Example
thisdict ={
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
25
Python Exception handling
Whenever an exception occurs, the program stops the execution, and thus the further code is not
executed. Therefore, an exception is the run-time errors that are unable to handle to Python
script. An exception is a Python object that represents an error
Python provides a way to handle the exception so that the code can be executed without any
interruption. If we do not handle the exception, the interpreter doesn't execute all the code that
exists after the exception.
Python has many built-in exceptions that enable our program to run without interruption and
give the output. These exceptions are given below:
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.
Example
try:
print(x)
except:
print("An exception occurred")
Output:
An exception occurred
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Example
Output:
Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in <module>
print(x)
NameError: name 'x' is not defined
• Error handling: The exceptions get raised whenever Python detects an error in a
program at runtime. As a programmer, if you don't want the default behavior, then code
a 'try' statement to catch and recover the program from an exception. Python will jump
to the 'try' handler when the program detects an error; the execution will be resumed.
• Event Notification: Exceptions are also used to signal suitable conditions & then passing
result flags around a program and text them explicitly.
27
• Terminate Execution: There may arise some problems or errors in programs that it
needs a termination. So try/finally is used that guarantees that closing-time operation
will be performed. The 'with' statement offers an alternative for objects that support it.
• Exotic flow of Control: Programmers can also use exceptions as a basis for
implementing unusual control flow. Since there is no 'go to' statement in Python so that
exceptions can help in this respect.
Example
The structure of such type of 'except' clause having no exception is shown with an example.
try:
......
All the exceptions get caught where there is try/except the statement of this type. Good
programmers use this technique of exception to make the program fully executable.
try:
# all operations are done within this block.
......
except ( Exception1 [, Exception2[,….Exception N ] ] ] ) :
28
# this block will get executed if any exception encounters from the above lists of exceptions.
......
else:
# this block will get executed if no exception is found.
......
Pytest
Pytest is a testing framework based on python. It is mainly used to write API test cases. This
tutorial helps you understand −
• Installation of pytest.
• Various concepts and features of pytest
Pytest is a python based testing framework, which is used to write and execute test codes. In the
present days of REST services, pytest is mainly used for API testing even though we can use
pytest to write simple to complex tests, i.e., we can write codes to test API, database, UI, etc.
Advantages of Pytest
The advantages of Pytest are as follows −
• Pytest can run multiple tests in parallel, which reduces the execution time of the test
suite.
• Pytest has its own way to detect the test file and test functions automatically, if not
mentioned explicitly.
• Pytest allows us to skip a subset of the tests during execution.
• Pytest allows us to run a subset of the entire test suite.
• Pytest is free and open source.
• Because of its simple syntax, pytest is very easy to start with.
29
Install pytest
Square.py
import math
def test_sqrt():
num = 25
assert math.sqrt(num) == 5
def testsquare():
num = 7
assert 7*7 == 40
def tesequality():
assert 10 == 11
output
E:\auto>pytest square.py
================================================================== test
session starts
===================================================================
platform win32 -- Python 3.9.0, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: E:\auto
collected 2 items
square.py .F
[100%]
=====================================================================
=== FAILURES
=====================================================================
===
_______________________________________________________________________
testsquare
_______________________________________________________________________
def testsquare():
num = 7
> assert 7*7 == 40
E assert (7 * 7) == 40
30
square.py:9: AssertionError
================================================================ short
test summary info
=================================================================
FAILED square.py::testsquare - assert (7 * 7) == 40
============================================================== 1 failed,
1 passed in 0.10s
===============================================================
MongoDB
MongoDB is a document-oriented, open-source database program that is platform-independent.
MongoDB, like some other NoSQL databases , stores its data in documents using a JSON
structure. This is what allows the data to be so flexible and not require a schema.
• You have support for many of the standard query types, like matching (==), comparison
(<, >), or even regex
• You can store virtually any kind of data - be it structured, partially structured, or even
polymorphic
• To scale up and handle more queries, just add more machines
• It is highly flexible and agile, allowing you to quickly develop your applications
• Being a document-based database means you can store all the information regarding your
model in a single document
• You can change the schema of your database on the fly
• Many relational database functionalities are also available in MongoDB (e.g. indexing)
As for the operations side of things, there are quite a few tools and features for MongoDB that
you just can’t find with any other database system:
31
If you take advantage of the indexing features, much of this data will be kept in memory for
quick retrieval. And even without indexing on specific document keys, Mongo caches quite a bit
of data using the least recently used method.
While at first Mongo may seem like it’s the solution to many of our database problems, it isn’t
without its drawbacks. One common drawback you’ll hear about Mongo is its lack of support for
ACID transactions. Mongo does support ACID transactions in a limited sense, but not in all
cases. At the single-document level, ACID transactions are supported (which is where most
transactions take place anyway). However, transactions dealing with multiple documents are not
supported due to Mongo’s distributed nature.
Mongo also lacks support for native joins, which must be done manually (and therefore much
more slowly). Documents are meant to be all-encompassing, which means, in general, they
shouldn’t need to reference other documents. In the real world this doesn’t always work as much
of the data we work with is relational by nature. Therefore many will argue that Mongo should
be used as a complementary database to a SQL DB, but as you use MongoDB you’ll find that is
not necessarily true.
Output:
E:\auto>python pymongoconnect.py
{'_id': ObjectId('5fd0945d020d5ae6da5ac9a9'),
'dept': 'CSE',
'name': 'RAM',
'regno': '1099'}
32
Check Databases
Check Collection
The following command is used to show available collection into the database
Python – MySQL
MySQL is an Open-Source database and one of the best type of RDBMS (Relational Database
Management System).
1. Installing MySQL
33
Download and install MySQL from the MySQL's official website. You need to install
the MySQL server to follow this tutorial.
Now, check whether you have installed the mysql.connector correctly or not using the
following code.
Import mysql.connector
If the above code runs without any errors, then you have successfully installed mysql.connector,
and it is ready to use.
34
2.1. Creating Databases
Now, we will create a database with the name klucse.
To create a database in MySQL, we use CREATE DATABASE database_name statement.
## creating an instance of 'cursor' class which is used to execute the 'SQL' statements in 'Python'
cursor = db.cursor()
If the database already exists you will get an error. Make sure that the database does not exist.
See all the databases present in MySQL using the following code.
To see all the databases we use SHOW DATABASES statement.
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "root",
passwd = "passwd"
)
cursor = db.cursor()
## 'fetchall()' method fetches all the rows from the last executed statement
databases = cursor.fetchall() ## it returns a list of all databases present
35
Creating Tables
Creating tables in the database to store the information. Before creating tables, we must select a
database first.
Run the following code, to select klucse database.
Use the CREATE TABLE table_name to create a table in the selected database.
db = mysql.connect(
host = "localhost",
user = "root",
passwd = "dbms",
database = "datacamp"
)
cursor = db.cursor()
You have successfully created the table users in the klucse database. See all the tables present in
the database using the SHOW TABLES statement.
36
Inserting Data
Inserting data into table to store it. Use INSERT INTO table_name (column_names)
VALUES (data) statement to insert into the table.
Inserting A Single Row
Let's see how to insert a single row into the table.
db = mysql.connect(
host = "localhost",
user = "root",
passwd = "passwd",
database = "klucse"
)
cursor = db.cursor()
## defining the Query
query = "INSERT INTO users (name) VALUES (%s)"
## storing values in a variable
values = ("K.L.University”)
## executing the query with values
cursor.execute(query, values)
## to make final output we have to run the 'commit()' method of the database object
db.commit()
print(cursor.rowcount, "record inserted")
37