0% found this document useful (0 votes)
7 views10 pages

Python Material 2024 TOPIC 8i

Uploaded by

hatim
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)
7 views10 pages

Python Material 2024 TOPIC 8i

Uploaded by

hatim
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/ 10

Python Material

TOPIC – 8 PYTHON OOPs CONCEPTS

Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python
modules, each with its specific work.
In this article, we will cover all about Python modules, such as How to create our own simple module,
Import Python modules, From statements in Python, we can use the alias to rename the module, etc.
What is Python Module
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also makes the code
logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file with .py extension. Let’s
understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and another subtract.

# A simple module, calc.py


def add(x, y):

return (x+y)

def subtract(x, y):

return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another module using the import
statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module is present in
the search path.
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Note: A search path is a list of directories that the interpreter searches for importing a module.
For example, to import the module calc.py, we need to put the following command at the top of the script.
Syntax to Import Module in Python
import module
Note: This does not import the functions or classes directly instead imports the module only. To access the
functions inside the module the dot(.) operator is used.
Importing modules in Python Example
Now, we are importing the calc that we created earlier to perform add operation.

# importing module calc.py

import calc

print(calc.add(10, 2))
Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a module without importing the module
as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the math module.
# importing sqrt() and factorial from the
# module math

from math import sqrt, factorial

# if we simply do "import math", then

# math.sqrt(16) and math.factorial()

# are required.

print(sqrt(16))

print(factorial(6))
Output:
4.0
720

2 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652


DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Import all Names
The * symbol used with the import statement is used to import all the names from a module to a current
namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the
module, it is not recommended to use *, else do so.

# importing sqrt() and factorial from the

# module math

from math import *

# if we simply do "import math", then

# math.sqrt(16) and math.factorial()

# are required.

print(sqrt(16))

print(factorial(6))
Output
4.0
720
Locating Python Modules

We can run the below command to get the all available modules in Python:
help('modules')

Whenever a module is imported in Python the interpreter looks for several locations. First, it will check for
the built-in module, if not found then it looks for a list of directories defined in the sys.path. Python
interpreter searches for the module in the following manner –
• First, it searches for the module in the current directory.
• If the module isn’t found in the current directory, Python then searches each directory in the shell
variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of
directories.
• If that also fails python checks the installation-dependent list of directories configured at the time
Python is installed.

3 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652


DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Directories List for Modules
Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the
interpreter will search for the required module.
# importing sys module

import sys

# importing sys.path

print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-dynload’, ”,
‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’,
‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]

Renaming the Python Module


We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name

# importing sqrt() and factorial from the

# module math

import math as mt

# if we simply do "import math", then

# math.sqrt(16) and math.factorial()

# are required.

print(mt.sqrt(16))

print(mt.factorial(6))
Output
4.0
720

4 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652


DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Python Built-in modules
There are several built-in modules in Python, which you can import whenever you like.

# importing built-in module math


import math

# using square root(sqrt) function contained


# in math module
print(math.sqrt(25))

# using pi function contained in math module


print(math.pi)

# 2 radians = 114.59 degrees


print(math.degrees(2))

# 60 degrees = 1.04 radians


print(math.radians(60))

# Sine of 2 radians
print(math.sin(2))

# Cosine of 0.5 radians


print(math.cos(0.5))

# Tangent of 0.23 radians


print(math.tan(0.23))

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

# importing built in module random


import random

# printing random integer between 0 and 5


print(random.randint(0, 5))

# print random floating point number between 0 and 1


print(random.random())

# random number between 0 and 100


print(random.random() * 100)
5 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
List = [1, 4, True, 800, "python", 27, "hello"]

# using choice function in random module for choosing


# a random element from a set such as a list
print(random.choice(List))

# importing built in module datetime


import datetime
from datetime import date
import time

# Returns the number of seconds since the


# Unix Epoch, January 1st 1970
print(time.time())

# Converts a number of seconds to a date object


print(date.fromtimestamp(454554))

Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87

We have covered Python Modules and it’s operations like create, import, etc. This article will give the
overview about Python modules so that you can easily create and use modules in Python

6 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652


DECENT COMPUTER INSTITUTE PYTHON MATERIAL
What is Object-Oriented Programming in Python?
In Python object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes
in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation,
etc. in the programming. The main concept of object-oriented Programming (OOPs) or oops concepts in
Python is to bind the data and the functions that work together as a single unit so that no other part of the
code can access this data. For more in-depth knowledge in Python OOPs concepts, try
GeeksforGeeks Python course, it will gives you insights of Python programming
OOPs Concepts in Python
• Class in Python
• Objects in Python
• Polymorphism in Python

Python Classes and Objects


A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means
of bundling data and functionality together. Creating a new class creates a new type of object, allowing
new instances of that type to be made. Each class instance can have attributes attached to it to maintain
its state. Class instances can also have methods (defined by their class) for modifying their state.
The class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint
for an object.

Creating a Python Class


Here, the class keyword indicates that you are creating a class followed by the name of the class (Dog in
this case).

class Dog:

sound = "bark"
Some points on Python class:
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator. Eg.: My
class.Myattribute

To understand the need for creating a class and object in Python let’s consider an example, let’s say you
wanted to track the number of dogs that may have different attributes like breed and age. If a list is used,
the first element could be the dog’s breed while the second element could represent its age. Let’s suppose
there are 100 different dogs, then how would you know which element is supposed to be which? What if
you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for
classes.

7 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652


DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Object of Python Class
In Python programming an Object is an instance of a Class. A class is like a blueprint while an instance is a
copy of the class with actual values.

obj = ClassName()
print(obj.atrr)
It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have
many dogs to create many different instances, but without the class as a guide, you would be lost, not
knowing what information is required.
An object consists of:
• State: It is represented by the attributes of an object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an object to
other objects.
• Identity: It gives a unique name to an object and enables one object to interact with other objects.

Declaring Class Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each
object. A single class may have any number of instances.
Example:

Example of Python Class and object


Creating an object in Python involves instantiating a class to create a new instance of that class. This
process is also referred to as object instantiation.
# instantiating a class

class Dog:
8 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL

# A simple class

# attribute

attr1 = "mammal"

attr2 = "dog"

# A sample method

def fun(self):

print("I'm a", self.attr1)

print("I'm a", self.attr2)

# Driver code

# Object instantiation

Rodger = Dog()

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()
Output:
mammal
I'm a mammal
I'm a dog

In the above example, an object is created which is basically a dog named Rodger. This class only has two
class attributes that tell us that Rodger is a dog and a mammal.

9 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652


DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Polymorphism in Python
What is Polymorphism: The word polymorphism means having many forms. In programming,
polymorphism means the same function name (but different signatures) being used for different types.
The key difference is the data types and number of arguments used in function.
Example of inbuilt polymorphic functions:
# Python program to demonstrate in-built poly-

# morphic functions

# len() being used for a string

print(len("decent"))

# len() being used for a list

print(len([10, 20, 30]))


Output
6
3

Examples of user-defined polymorphic functions:


# A simple Python function to demonstrate

# Polymorphism

def add(x, y, z = 0):

return x + y+z

# Driver code

print(add(2, 3))

print(add(2, 3, 4))
Output
5
9

10 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652

You might also like