Module and Importing
- Every single .py file or a python script file is a separate module in python.
- Suppose if your application have 2 .py(python script) file, then you application have 2 modules.
- to use one module (identifiers from one module) to other, we need to import the module to other.
- Importing is done with the keyword import
Syntax:
keyword_import _module name
to use identifiers / variables from imported module, we use module_name
module_name.variable.identifier_name
with import we can import
- full module
- single/multiple function
- single/multiple Class object
- combination of function variable and class object.
let's we have a module file1.py as below
#program in file1.py
a=10
b=20
def add():
return a+b;
now we are in need to import file1.py in file2.py
Few ways of importing a module and how to get access to its content(variable/function)
case 1: import module
- here we are importing module
- we need to use module name to access content(variable/function) in module file1.py
#program in file2.py
import file1
print("a :",file1.a)
print("b :",file1.b)
result = file1.add()
print("sum is : ",result)
Output will be
a : 10
b : 20
sum is : 30
case 2: import module as alias
- here we are importing module file1 as f1(alias)
- we can access files 1 content(variable/function) with this alias name
#program in file2.py
import file1 as f1
print("a :",f1.a)
print("b :",f1.b)
result = f1.add()
print("sum is : ",result)
Output will be
a : 10
b : 20
sum is : 30
case 3: from module import all
- to import all data we use *(star)
- directly we can access file 1 content(variable/function) without imported module name reference
#program in file2.py
from file1 import *
print("a :",a)
print("b :",b)
result = add()
print("sum is : ",result)
Output will be
a : 10
b : 20
sum is : 30
case 4: from module import specific(variable/function/class object)
- we are importing only variable a and b
- we can directly call content(variable/function) of module file1.py by name
#program in file2.py
from file1 import a,b
print("a :",a)
print("b :",b)
result = add()
print("sum is : ",result)
output will be
a : 10
b : 20
Traceback (most recent call last):
File "C:\Self_Practice_Er_M_S_Dandyan\Python\file2.py", line 6, in <module>
result = add()
NameError: name 'add' is not defined
As we have not imported function add() from file.1, so we cannot use it in file2.py
Comments
Post a Comment