INDEX
[Link] DATE Title Page No. Remarks
ADVANCED PYTHON
Practical [Link] in Python :
Object-Oriented Programming (OOP) in Python is a programming paradigm that
organizes code by modeling real-world entities as objects. Each object in Python has
attributes (data) and methods (functions) that operate on the data. Here are the key
concepts:
Major principles of object-oriented programming system are given below.
o Classes and Objects
o Encapsulation
o Abstraction
o Inheritance
o Polymorphism
o Contructors and Destructors
Classes and Objects :
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.
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.
SOURCE CODE :-
OUTPUT :
Encapsulation :
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are
wrapped together within a single unit from being modified by accident.
SOURCE CODE :
OUTPUT :
Abstractions :
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.
SOURCE CODE :
OUTPUT :
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.
SOURCE CODE :
OUTPUT :
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".
SOURCE CODE :
OUTPUT :
Constructor :
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
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.
Non-Parameterized Constructor :
The non-parameterized constructor uses when we do not want to manipulate the
value or the constructor that has only self as an argument.
Parameterized Constructor
The parameterized constructor has multiple parameters along with the self.
SOURCE CODE :
OUTPUT :
Destructors :
The users call Destructor for destroying the object. In Python, developers might not
need destructors as much it is needed in the C++ language. This is because Python has
a garbage collector whose function is handling memory management automatically.
The __del__() function is used as the destructor function in Python. The user can call
the __del__() function when all the references of the object have been deleted, and it
becomes garbage collected.
SOURCE CODE :
OUTPUT :
Pratical no 2. Classes and Objects :
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.
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.
The self variable :
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:
SOURCE CODE :
OUTPUT :
Type of variable :
Instance Variables (name, age): Defined in the __init__ method. Unique to each
instance (e.g., [Link] and [Link] are different).
Variables that are unique to each instance (object) of a class. These are defined
within __init__ method or other instance methods. Each object maintains its own
copy of instance variables, independent of other objects.
SOURCE CODE :
OUTPUT :
Class Variables
These are the variables that are shared across all instances of a class. It is defined at
the class level, outside any methods. All objects of the class share the same value for
a class variable unless explicitly overridden in an object.
Class Variable (species): Shared by all instances of the class. Changing [Link]
affects all objects, as it’s a property of the class itself.
SOURCE CODE :
OUTPUT :
Pratical no 3. Inheritance and polymorphism :
Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
The term polymorphism refers to a function or method taking different forms in
different contexts. Since Python is a dynamically typed language, polymorphism in
Python is very easily implemented.
Example:
CODE :
OUTPUT :
I. Duck Typing
II. Operator Overloading
III. Method Overriding
IV. Method Overloading
Duck Typing:
Duck typing is a concept where the type or class of an object is less important than
the methods it defines. Using this concept, you can call any method on an object
without checking its type, as long as the method exists.
OUTPUT :
Method Overriding
In method overriding, a method defined inside a subclass has the same name as a
method in its superclass but implements a different functionality.
OUTPUT :-
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional
vectors, what happens when you use the plus operator to add them.
OUTPUT :
Method Overloading
When a class contains two or more methods with the same name but different
number of parameters then this scenario can be termed as method overloading.
Python does not allow overloading of methods by default, however, we can use the
techniques like variable-length argument lists, multiple dispatch and default
parameters to achieve this.
OUTPUT :
Pratical no 4. Abstract Base Classes and Interfaces :
It defines methods that must be implemented by its subclasses, ensuring
that the subclasses follow a consistent structure. ABCs allow you to
define common interfaces that various subclasses can implement while
enforcing a level of abstraction.
OUTPUT :
Interfaces
In languages like Java and Go, there is keyword called interface which is used to
define an interface. Python doesn't have it or any similar keyword. It uses abstract
base classes (in short ABC module) and @abstractmethod decorator to create
interfaces.
Ways to implement Interfaces
Formal Interface
Informal Interface
Formal Interface
Formal interfaces in Python are implemented using abstract base class (ABC). To use
this class, you need to import it from the abc module.
OUTPUT :
Informal Interface
In Python, the informal interface refers to a class with methods that can be
overridden. However, the compiler cannot strictly enforce the implementation of all
the provided methods.
This type of interface works on the principle of duck typing. It allows us to call any
method on an object without checking its type, as long as the method exists.
OUTPUT :
Pratical no 5. Database Connection :
In this section of the tutorial, we will discuss the steps to connect the python
application to the [Link] are the following steps to connect a python
application to our database.
1. Import [Link] module
2. Create the connection object.
3. Create the cursor object
4. Execute the query
Creating the connection :
Creating a cursor object
The cursor object can be defined as an abstraction specified in the Python DB-API 2.0.
It facilitates us to have multiple separate working environments through the same
connection to the database. We can create the cursor object by calling the 'cursor'
function of the connection object. The cursor object is an important aspect of
executing queries to the databases.
Creating new databases :
Creating the table
In this section of the tutorial, we will create the new table Employee. We
have to mention the database name while establishing the connection
object.
We can create the new table by using the CREATE TABLE statement of
SQL. In our database PythonDB, the table Employee will have the four
columns, i.e., name, id, salary, and department_id initially.
OUTPUT :
Insert multiple rows :
Delete Operation
The DELETE FROM statement is used to delete a specific record from the table. Here,
we must impose a condition using WHERE clause otherwise all the records from the
table will be removed.
Pratical no 6. Exceptions in python :
Exception Handling handles errors that occur during the execution of a program.
Exception handling allows to respond to the error, instead of crashing the running
program. It enables you to catch and manage errors, making your code more robust
and user-friendly.
ZeroDivisionError :
OUTPUT :
ValueError:
OUTPUT :
IndexError:
OUTPUT :
ArithmeticError:
OUTPUT :
Pratical no 7. Networking :
Networking in Python is a powerful way to communicate between devices, services,
or applications. With Python, you can build client-server applications, send data over
networks, and work with protocols like HTTP, FTP, and SMTP. Here's a quick guide to
networking in Python:
1. Basic Networking Concepts
Socket Programming: The core of networking in Python is the socket module.
It provides low-level networking interfaces like creating sockets, connecting to
other machines, and sending/receiving data.
Client-Server Model: In this model, the server listens for incoming connections,
and the client establishes a connection to the server to send or receive data.
Simple Client :
Output :
Server side :
Output:
Pratical no 8. Graphical User Interface(GUI) :
A GUI (Graphical User Interface) in Python allows developers to create desktop
applications with graphical elements like buttons, windows, and text fields, enabling
users to interact with the program visually.
To build GUIs in Python, you typically use libraries like:
Tkinter: A built-in library in Python for creating simple GUIs. It provides basic widgets
like buttons, labels, textboxes, and more.
PyQt / PySide: More advanced libraries based on the Qt framework, offering
features for creating complex and professional interfaces.
Kivy: Suitable for multi-touch applications and can be used for mobile apps.
wxPython: Another library for creating cross-platform desktop applications with
native look and feel.
Basic code for Tkinter :
Output :
Canvas :
Output :
Change background color using button :
Output :
Check button :
Output :
Label :
Output :
Frame:
Output :
Moon Pratical :
Output :
Pratical no 9. Threads in python :
In Python, threads allow you to run multiple tasks simultaneously within a single
program, making it easier to handle tasks that can run independently, such as I/O
operations or long-running computations.
Thread: A lightweight process that runs independently but shares the same memory
space within a program.
Concurrency: Threads allow multiple tasks to progress at the same time, improving
efficiency for certain operations.
Global Interpreter Lock (GIL): In CPython (the standard Python implementation), the
GIL prevents multiple threads from executing Python bytecode at once, so threading
is not ideal for CPU-bound tasks, but it’s useful for I/O-bound tasks (like file
reading/writing or network operations).
Basic code of threads :
Output :
Creating thread using class :
Output :
Creating thread using sub-class :
Output :
Single tasking thread in python :
Output :
Pratical no 10. Date and Time in python :
In Python, the datetime module is used to work with dates and times. It
provides classes to manipulate dates, times, and intervals in both simple
and complex ways.
Key Components:
1. date: Represents a date (year, month, day).
2. time: Represents a time (hours, minutes, seconds, microseconds).
3. datetime: Combines both date and time (year, month, day, hour,
minute, second).
4. timedelta: Represents the difference between two dates or times
(duration).
Basic code for date and time :
Output :
Combining Date and time :
Output :
Formattting Dates and Times :
Output :
Finding Durations using “delta time “ :
Output :
Camparing two dates :
Output :
Sorting Dates :
Output :
Stopping Execution Temporarily :
Output :
Knowing the Time Taken by a program :
Output :
Calendar Module :
Output :
Pratical no 11. Working with files :
Working with files in Python involves several key operations such as reading, writing,
and deleting files. To open a file, you can use the open() function, specifying the file
name and mode, such as "r" for reading, "w" for writing, "a" for appending, and "x"
for creating a new file.
For reading files, you can use methods like read(), readlines(), or iterate over the file
object to read lines one by one. When writing to a file, you can use write() or
writelines() to add data.
Opening() and Closing() File :
Output :
Working with text files containing strings :
Output :
Knowing whether a file exists or not :
Output :
Working with binary files :
Output :
The seek() and tell() methods :
Output :
Random accessing of binary file :
Output :
Zipping and Unzipping files :
Output :
Output :
Working with directories :
Output :
Running other programs from python program :
Output :
Pratical no 12. Regular Expressions :
In Python, Regular Expressions (regex) are used for searching, matching, and
manipulating text based on patterns. Python's re module provides functions for
working with regular expressions.
Common Meta-characters:
.: Any character except newline.
^: Start of the string.
$: End of the string.
*: 0 or more occurrences of the preceding pattern.
+: 1 or more occurrences of the preceding pattern.
[]: Matches any character inside the brackets.
\d: Digit (equivalent to [0-9]).
\w: Word character (letters, digits, and underscores).
\s: Whitespace character (space, tab, newline).
Output :