UNIT-3 Python
UNIT-3 Python
Python Modules
A python module can be defined as a python program file which contains a
python code including python functions, class, or variables. In other words, we
can say that our python code file saved with the extension (.py) is treated as the
module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical
way.
To use the functionality of one module into another, we must have to import the
specific module.
Example
In this example, we will create a module named as file.py which contains a
function func that contains a code to print some message on the console.
Let's create the module named as file.py.
#displayMsg prints a message to the name being passed.
def displayMsg(name)
print("Hi "+name);
Here, we need to include this module into our main module to call the method
displayMsg()defined in the module named file.
Modules in python
In Python, a module is a file containing Python code that can define functions,
classes, and variables. You can use modules to organize your code into logical
units, making it easier to manage and reuse.
Definition: A module is a file containing Python definitions and
statements. The file name is the module name with the suffix .py appended.
Python has no main function or method. Instead, there is a main module. The
main module is the source file that runs first. Whatever file you give to the
interpreter at startup becomes main.
Example:
# mymodule.py
def greet(name):
print("Hello, " + name)
Now, let's use this module in another Python file:
Python
# main.py
import mymodule
mymodule.greet("Alice")
Output:
Hello, Alice
Built-in Modules:
Python comes with many built-in modules that provide a wide range of
functionalities. Here are a few examples:
math: Provides mathematical functions like sqrt, sin, cos, etc.
random: Generates random numbers and sequences.
DateTime: Manipulates dates and times.
os: Interacts with the operating system.
json: Encodes and decodes JSON data.
What is a package in Python?Python Packages are a way to organize and
structure your Python code into reusable components. Think of it like a folder
that contains related Python files (modules) that work together to provide
certain functionality.
Python Packages are a way to organize and structure your Python code into
reusable components. Think of it like a folder that contains related Python files
(modules) that work together to provide certain functionality. Packages help
keep your code organized, make it easier to manage and maintain, and allow
you to share your code with others. They’re like a toolbox where you can store
and organize your tools (functions and classes) for easy access and reuse in
different projects.
How to Create Package in Python?
Creating packages in Python allows you to organize your code into reusable and
manageable modules. Here’s a brief overview of how to create packages:
Create a Directory: Start by creating a directory (folder) for your package.
This directory will serve as the root of your package structure.
Add Modules: Within the package directory, you can add Python files
(modules) containing your code. Each module should represent a distinct
functionality or component of your package.
Init File: Include an __init__.py file in the package directory. This file can be
empty or can contain an initialization code for your package. It signals to
Python that the directory should be treated as a package.
Subpackages: You can create sub-packages within your package by adding
additional directories containing modules, along with their own __init__.py
files.
Importing: To use modules from your package, import them into your Python
scripts using dot notation. For example, if you have a module named
module1.py inside a package named mypackage, you would import its function
like this: from mypackage.module1 import greet.
Distribution: If you want to distribute your package for others to use, you can
create a setup.py file using Python’s setuptools library. This file defines
metadata about your package and specifies how it should be installed.
Code Example
Here’s a basic code sample demonstrating how to create a simple Python
package:
Create a directory named mypackage.
Inside mypackage, create two Python files: module1.py and module2.py.
Create an __init__.py file inside mypackage (it can be empty).
Add some code to the modules.
Finally, demonstrate how to import and use the modules from the package.
mypackage/
│
├── __init__.py
├── module1.py
└── module2.py
Example: Now, let’s create a Python script outside the mypackage directory to
import and use these modules:
# module1.py
def greet(name):
print(f"Hello, {name}!")
output:
Hello, Alice!
The result of addition is: 8
What is standalone in Python?
Python programs can be written as independent commands (like other basic
Linux commands). These progams do not require an interactive environemnt
(like jupyter notebook). In this tutorial, a simple application (vcorner) is used to
illustrate the development of a standalone program.
What Is a Standalone Application?
A standalone application, also known as a desktop application is a software
program designed in such a way that to run this software program, users don’t
need an internet connection or any server access. Web-based applications need
an internet connection, servers, and any additional resources to run but
standalone applications do not require any additional resources such as an
internet connection, server, etc.
Where Can a Standalone Application Be Used?
A standalone application is used when a user wants to perform any specific task
on a local machine, without the requirement of an internet connection to the
system. Desktop software, Mobile apps, Gaming Applications, Industrial
control systems Medical Devices, etc. are some examples where standalone
applications are developed frequently.
Features:
Offline functionality: If the user uses standalone applications then do not
require an internet connection to run it, which makes them ideal for users who
may not have a stable internet connection.
Better performance: Standalone applications directly run on the user’s device
without the need for an internet connection, and because of that standalone
application provides faster performance and a better user experience.
Greater control: Standalone applications do not depend on outside servers to
store their data, so users have more control over their data when using the
standalone applications.
Simple distribution: These applications can easily make available to a large
number of users using the app store or any other platforms
Cost-effectiveness: Standalone applications run on the local machines of users
and do not require any server to store the data. So these types of applications are
less expensive and easy to design and operate.
What Is the Future of Standalone Applications?
As mobile devices become more powerful and obvious to use, independent apps
made for mobile platforms are anticipated to grow more popular.
Integration of stand-alone applications with cloud-based services is becoming
more common, and because of it. it enables users to store and access data from
any location.
The emergence of new technologies, such as augmented reality and virtual
reality, may open up new possibilities for standalone apps that make use of
these technologies..
Standalone Application vs Client-Server Application:
Standalone Application Client-Server Application
Output
3.141592653589793
Import Python Built-In Modules
In this example, the built-in ‘random’ module is imported in Python using
the import statement. The randint function from the ‘random’ module is then utilized
to generate a random integer between 1 and 10, and the result is printed. We can
also import a file in Python by using import statement.
Python3
# Import the 'random' module, which is a built-in module for random number generation
import random
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
print("Random Number:", random_number)
Output
Random Number: 5
Import a Module and Assign an Alias in Python
In this example, the ‘math’ module is imported with the alias ‘m’ using
the import statement. The sqrt function from the ‘math’ module, accessed through the
alias ‘m’, is then used to calculate the square root of 25. The result is printed as
“Square root of 25.
Python3
# Import the 'math' module with the alias 'm'
import math as m
# Use functions from the 'math' module with the alias
result = m.sqrt(25)
print("Square root of 25:", result)
Output
Square root of 25: 5.0
Importing `*` in Python
In the above code module, math is not imported, rather just pi has been imported as
a variable.
All the functions and constants can be imported using *.
Python3
from math import *
print(pi)
print(factorial(6))
Output
3.141592653589793
720
import uses __import__() to search for the module, and if not found, it would raise
ImportError
Python3
import mathematics
print(mathematics.pi)
Output:
Traceback (most recent call last):
File "C:/Users/GFG/Tuples/xxx.py", line 1, in
import mathematics
ImportError: No module named 'mathematics'
Python Classes and Objects
An object is an instance of a class.
Think of a class as a blueprint or a template, and an object as a specific
realization of that blueprint.
Objects have attributes (data) and methods (functions) that define their
characteristics and behavior.
Everything in Python is an object, including numbers, strings, lists, and even
functions.
Example:
Execution output
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
# Creating an object of the Dog class
my_dog = Dog("Buddy", "Golden Retriever")
# Accessing attributes
print(my_dog.name)
print(my_dog.breed)
# Calling methods
my_dog.bark()
Buddy
Golden Retriever
Woof!
object():
This is the base class for all classes in Python.
All classes inherit from object either directly or indirectly.
It provides some basic functionality that all objects have, such as:
__init__: The constructor method, called when an object is created
__str__: Defines how an object is represented as a string
__repr__: Defines a more detailed string representation of an object, typically
used for debugging
A class in Python is a user-defined template for creating objects. It bundles data
and functions together, making it easier to manage and use them. When we
create a new class, we define a new type of object. We can then create multiple
instances of this object type.
Classes are created using class keyword. Attributes are variables defined inside
the class and represent the properties of the class. Attributes can be accessed
using the dot . operator (e.g., MyClass.my_attribute).
Create a Class
# define a class
class Dog:
sound = "bark" # class attribute
Create Object
An Object is an instance of a Class. It represents a specific implementation of
the class and holds its own data.
Now, let’s create an object from Dog class.
class Dog: sound = "bark"
# Create an object from the class
dog1 = Dog()
# Access the class attribute
print(dog1.sound)
Output
Canine
Buddy
Charlie
Max
Feline
Feline
Explanation:
Class Variable (species): Shared by all instances of the class. Changing
Dog.species affects all objects, as it’s a property of the class itself.
Instance Variables (name, age): Defined in the __init__ method. Unique to
each instance (e.g., dog1.name and dog2.name are different).
Accessing Variables: Class variables can be accessed via the class name
(Dog.species) or an object (dog1.species). Instance variables are accessed via
the object (dog1.name).
Updating Variables: Changing Dog.species affects all instances. Changing
dog1.name only affects dog1 and does not impact dog2.
What are classes and objects in Python?
Classes in Python are blueprints for creating objects. They define the attributes
(data) and methods (functions) that objects of the class will have.
Objects are instances of classes. They are created from the class blueprint and
can have their own unique data while sharing common methods defined in the
class.
What is Python class type?
In Python, a class type refers to the type of object that a class creates. It defines
the structure and behavior of objects instantiated from that class.
Why use classes in Python?
Classes in Python provide a way to structure and organize code into reusable
components. They facilitate code reusability, modularity, and maintainability by
encapsulating data (attributes) and functionality (methods) within objects.
How to define a class in Python?
To define a class in Python, use the class keyword followed by the class name
and a colon (:). Inside the class block, define attributes and methods.
class MyClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def some_method(self):
# Method definition
pass
What is an object in OOP?
In Object-Oriented Programming (OOP), an object is a tangible entity that
represents a particular instance of a class. It combines data (attributes) and
behaviors (methods) specified by the class.
Why do we need classes and objects?
Classes and objects provide a way to model real-world entities and abstract
concepts in code. They promote code organization, encapsulation (data hiding),
inheritance (code reuse), and polymorphism (method overriding), making
complex systems easier to manage and extend.
In Python, a class is a blueprint for creating objects. It defines a set of attributes
and methods that the objects of that class will have.
Here's how you define a class:
Python
class MyClass:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, my name is {self.name}")
Explanation:
class MyClass:: This line declares a new class named MyClass.
def __init__(self, name):: This is the constructor method. It's automatically
called when you create an object of the class. It initializes the object's
attributes. In this case, it takes a name argument and assigns it to
the self.name attribute.
def say_hello(self):: This is a method that can be called on objects of the
class. It prints a greeting using the object's name attribute.
To create an object of the class and use its methods:
Python
obj = MyClass("John")
obj.say_hello()
Python
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello, my name is", self.name)
Explanation:
class MyClass:: This line defines a new class named MyClass.
def __init__(self, name):: This is the constructor method that initializes the
object when it is created. It takes a parameter name and assigns it to
the self.name attribute.
def greet(self):: This is a method that prints a greeting using the
object's name attribute.
How to use:
Python
obj = MyClass("Alice") # Create an object of the class
obj.greet() # Call the greet method on the object
define a class with class in python
Such a class is called a "nested class." Nested classes are considered to be
within the scope of the enclosing class and are available for use within that
scope. To refer to a nested class from a scope other than its immediate enclosing
scope, you must use a fully qualified name
Python Class
Python is a completely object-oriented language. You have been working
with classes and objects right from the beginning of these tutorials. Every
element in a Python program is an object of a class. A number, string, list,
dictionary, etc., used in a program is an object of a corresponding built-in
class. You can retrieve the class nsame of variables or objects using
the type() method, as shown below.
Example: Python Built-in Classes
num=20
print(type(num)) #<class 'int'>
s="Python"
print(type(s)) #<class 'str'>
Try it
Defining a Class
A class in Python can be defined using the class keyword.
class <ClassName>: <statement1> <statement2> . . <statementN>
As per the syntax above, a class is defined using the class keyword followed
by the class name and : operator after the class name, which allows you to
continue in the next indented line to define class members. The followings
are class members.
Class Attributes
Constructor
Instance Attributes
Properties
Class Methods
A class can also be defined without any members. The following example
defines an empty class using the pass keyword.
Example: Define Python Class
Copy
class Student:
pass
Class instantiation uses function notation. To create an object of the class,
just call a class like a parameterless function that returns a new object of the
class, as shown below.
Example: Creating an Object of a Class
Copy
std = Student()
Above, Student() returns an object of the Student class, which is assigned to
a local variable std. The Student class is an empty class because it does not
contain any members.
Class Attributes
Class attributes are the variables defined directly in the class that are shared
by all objects of the class. Class attributes can be accessed using the class
name as well as using the objects.
Example: Define Python Class
Copy
class Student:
schoolName = 'XYZ School'
Above, the schoolName is a class attribute defined inside a class. The value
of the schoolName will remain the same for all the objects unless modified
explicitly.
Example: Define Python Class
print(Student.schoolName) #'XYZ School'
Student.schoolName = 'ABC School'
print(Student.schoolName) #'ABC School'
std = Student()
print(std.schoolName) #'ABC School'
std.schoolName = 'Super School'
print(std.schoolName) #'Super School'
print(Student.schoolName) #'ABC School'
Try it
As you can see, a class attribute is accessed by Student.schoolName as well
as std.schoolName. Changing the value of class attribute using the class
name would change it across all instances. However, changing class attribute
value using instance does not reflect to other instances or class.
The following example demonstrates the use of class attribute count.
Example: Student.py
Copy
class Student:
count = 0
def __init__(self):
Student.count += 1
In the above example, count is an attribute in the Student class. Whenever a
new object is created, the value of count is incremented by 1. You can now
access the count attribute after creating the objects, as shown below.
Example:
std1=Student()
print(Student.count) #1
std2 = Student()
print(Student.count) #2
std3 = Student()
print(Student.count) #3
Try it
Constructor
In Python, the constructor method is invoked automatically whenever a new
object of a class is instantiated, same as constructors in C# or Java. The
constructor must have a special name __init__() and a special parameter
called self.
The first parameter of each method in a class must be the self , which refers
to the calling object. However, you can give any name to the first parameter,
not necessarily self.
The following example defines a constructor.
Example: Constructor
class Student:
def __init__(self): # constructor method
print('Constructor invoked')
s1 = Student()
s2 = Student()
Try it
In the above example, whenever you create an object of the Student class,
the __init__() constructor method will be called.
In Python, the constructors are mostly used to define instance attributes and
assign their default values.
Instance Attributes
Instance attributes are attributes or properties attached to an instance of a
class. Instance attributes are defined in the constructor.
The following example defines instance attributes name and age in the
constructor.
Example: Instance Attributes
class Student:
schoolName = 'XYZ School' # class attribute
def __init__(self): # constructor
self.name = '' # instance attribute
self.age = 0 # instance attribute
You can get or set the value of instance attributes using the dot
notation: [instance name].[attribute name], as shown below.
Example: Get or Set Instance Attributesstd = Student()
print(std.name) #''
print(std.age) #0
std.name = "Bill"
std.age=25
print(std.name) #'Bill'
print(std.age) #25
Try it
You can specify the values of instance attributes through the constructor.
The following constructor includes the name and age parameters, other than
the self parameter.
Example: Setting Attribute Values
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
std = Student('Bill',25) #passing values to constructor
print(std.name)
print(std.age)
Try it
As you can see, you can pass the attributes value while creating an instance.
You don't have to specify the value of the self parameter. It will be assigned
internally in Python.
You can also set default values to the instance attributes. The following code
sets the default values of the constructor parameters. So, if the values are not
provided when creating an object, the values will be assigned latter.
Example: Setting Default Values of Attributes
class Student:
def __init__(self, name="Guest", age=25)
self.name=name
self.age=age
std = Student()
print(std.name) #'Guest'
print(std.age) #25
Try it
Visit class attributes vs instance attributes in Python for more information.
Class Properties
In Python, a property in the class can be defined using the property()
function.
The property() method in Python provides an interface to instance attributes.
It encapsulates instance attributes and provides a property, same as Java and
C#.
The property() method takes the get, set and delete methods as arguments
and returns an object of the property class.
The following example demonstrates how to create a property in Python
using the property() function.
Example: property()
class Student:
def displayInfo(self): # class method
print('Student Information')
#create object
std = Student()
std.displayInfo() #calling method
Try it
In the above displayInfo() method, self is just a conventional name for the
first argument. The method can be called as object.method().
The first parameter of the method need not be named self. You can give any
name that refers to the instance of the calling method. The
following displayInfo() method names the first parameter as obj instead
of self and that works perfectly fine.
Example: Class Method
Copy
class Student:
def displayInfo(obj): # class method
print('Student Information')
Defining a method in the class without the self parameter would raise an
exception when calling a method.
Example: Method without self
class Student:
def displayInfo(): # method without self parameter
print('Student Information')
std = Student()
std.displayInfo() #error
The method can access instance attributes using the self parameter.
Example: Class Method
Copy
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def displayInfo(self): # class method
print('Student Name: ', self.name,', Age: ', self.age)
You can now invoke the method, as shown below.
Example: Calling a Method
Copy
std = Student('Steve', 25)
std.displayInfo()
Try it
Deleting Attribute, Object, Class
You can delete attributes, objects, or the class itself, using the del keyword,
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def displayInfo(self): # class method
print('Student Name: ', self.name,', Age: ', self.age)
std = Student('Steve', 25)
std.displayInfo()
del std.name # deleting attribute
print(std.name) #error
del std
print(std.name) #error
del Student # deleting class
std = Student('Steve', 25) #error
Inheritance in Python
We often come across different products that have a basic model and an
advanced model with added features over and above basic model. A software
modelling approach of OOP enables extending the capability of an existing
class to build a new class, instead of building from scratch. In OOP
terminology, this characteristic is called inheritance, the existing class is
called base or parent class, while the new class is called child or sub class.
Inheritance comes into picture when a new class possesses the 'IS A'
relationship with an existing class.
Dog IS an animal. Cat also IS an animal. Hence, animal is the base class,
while dog and cat are inherited classes.
A quadrilateral has four sides. A rectangle IS a quadrilateral, and so IS a
square. Quadrilateral is a base class (also called parent class), while
rectangle and square are the inherited classes - also called child classes.
The child class inherits data definitions and methods from the parent class.
This facilitates the reuse of features already available. The child class can
add a few more definitions or redefine a base class method.
This feature is extremely useful in building a hierarchy of classes for objects
in a system. It is also possible to design a new class based upon more than
one existing classes. This feature is called multiple inheritance.
The general mechanism of establishing inheritance is illustrated below:
Syntax:
class parent: statements class child(parent): statements
While defining the child class, the name of the parent class is put in the
parentheses in front of it, indicating the relation between the two. Instance
attributes and methods defined in the parent class will be inherited by the
object of the child class.
To demonstrate a more meaningful example, a quadrilateral class is first
defined, and it is used as a base class for the rectangle class.
A quadrilateral class having four sides as instance variables and
a perimeter() method is defined below:
Example:
class quadriLateral:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print("perimeter=",p)
q1=quadriLateral(7,5,6,4)
q1.perimeter()
Try it
The constructor (the __init__() method) receives four parameters and assigns
them to four instance variables. To test the above class, declare its object
and invoke the perimeter() method.
We now design a rectangle class based upon the quadriLateral class
(rectangle IS a quadrilateral!). The instance variables and
the perimeter() method from the base class should be automatically available
to it without redefining it.
Since opposite sides of the rectangle are the same, we need only two
adjacent sides to construct its object. Hence, the other two parameters of
the __init__() method are set to none. The __init__() method forwards the
parameters to the constructor of its base (quadrilateral) class using
the super() function. The object is initialized with side3 and side4 set to
none. Opposite sides are made equal by the constructor of rectangle class.
Remember that it has automatically inherited the perimeter() method, hence
there is no need to redefine it.
Example: Inheritance
Copy
class quadriLateral:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print("perimeter=",p)
class rectangle(quadriLateral):
def __init__(self, a, b):
super().__init__(a, b, a, b)
r1=rectangle(10, 20)
r1.perimeter()
Try it
We can now declare the object of the rectangle class and call
the perimeter() method.
Overriding in Python
In the above example, we see how resources of the base class are reused
while constructing the inherited class. However, the inherited class can have
its own instance attributes and methods.
Methods of the parent class are available for use in the inherited class.
However, if needed, we can modify the functionality of any base class
method. For that purpose, the inherited class contains a new definition of a
method (with the same name and the signature already present in the base
class). Naturally, the object of a new class will have access to both methods,
but the one from its own class will have precedence when invoked. This is
called method overriding.
First, we shall define a new method named area() in the rectangle class and
use it as a base for the square class. The area of rectangle is the product of
its adjacent sides.
Example: Overriding Class
Copy
class quadriLateral:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print("perimeter=",p)
class rectangle(quadriLateral):
def __init__(self, a,b):
super().__init__(a, b, a, b)
def area(self):
a = self.side1 * self.side2
print("area of rectangle=", a)
Let us define the square class which inherits the rectangle class.
The area() method is overridden to implement the formula for the area of the
square as the square of its sides.
Example: Overriding Class
Copy
class square(rectangle):
def __init__(self, a):
super().__init__(a, a)
def area(self):
a=pow(self.side1, 2)
print('Area of Square: ', a)
s=square(10)
s.area() #output: Area of Square: 100