SlideShare uma empresa Scribd logo
1 de 4
Baixar para ler offline
http://www.tutorialspoint.com/python/python_modules.htm Copyright © tutorialspoint.com
PYTHON MODULES
A module allows youto logically organize your Pythoncode. Grouping related code into a module makes the
code easier to understand and use. A module is a Pythonobject witharbitrarily named attributes that youcanbind
and reference.
Simply, a module is a file consisting of Pythoncode. A module candefine functions, classes and variables. A
module canalso include runnable code.
Example:
The Pythoncode for a module named aname normally resides ina file named aname.py. Here's anexample of a
simple module, support.py
def print_func( par ):
print "Hello : ", par
return
The import Statement:
Youcanuse any Pythonsource file as a module by executing animport statement insome other Pythonsource
file. The import has the following syntax:
import module1[, module2[,... moduleN]
Whenthe interpreter encounters animport statement, it imports the module if the module is present inthe search
path. A searchpathis a list of directories that the interpreter searches before importing a module. For example,
to import the module hello.py, youneed to put the following command at the top of the script:
#!/usr/bin/python
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
Whenthe above code is executed, it produces the following result:
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the module
executionfromhappening over and over againif multiple imports occur.
The from...import Statement
Python's from statement lets youimport specific attributes froma module into the current namespace. The
from...import has the following syntax:
from modname import name1[, name2[, ... nameN]]
For example, to import the functionfibonaccifromthe module fib, use the following statement:
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces the item
fibonaccifromthe module fib into the globalsymboltable of the importing module.
The from...import * Statement:
It is also possible to import allnames froma module into the current namespace by using the following import
statement:
from modname import *
This provides aneasy way to import allthe items froma module into the current namespace; however, this
statement should be used sparingly.
Locating Modules:
Whenyouimport a module, the Pythoninterpreter searches for the module inthe following sequences:
The current directory.
If the module isn't found, Pythonthensearches eachdirectory inthe shellvariable PYTHONPATH.
If allelse fails, Pythonchecks the default path. OnUNIX, this default pathis normally
/usr/local/lib/python/.
The module searchpathis stored inthe systemmodule sys as the sys.path variable. The sys.pathvariable
contains the current directory, PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable:
The PYTHONPATH is anenvironment variable, consisting of a list of directories. The syntax of PYTHONPATH
is the same as that of the shellvariable PATH.
Here is a typicalPYTHONPATH froma Windows system:
set PYTHONPATH=c:python20lib;
And here is a typicalPYTHONPATH froma UNIX system:
set PYTHONPATH=/usr/local/lib/python
Namespaces and Scoping:
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and
their corresponding objects (values).
A Pythonstatement canaccess variables ina local namespace and inthe global namespace. If a localand a global
variable have the same name, the localvariable shadows the globalvariable.
Eachfunctionhas its ownlocalnamespace. Class methods follow the same scoping rule as ordinary functions.
Pythonmakes educated guesses onwhether variables are localor global. It assumes that any variable assigned
a value ina functionis local.
Therefore, inorder to assigna value to a globalvariable withina function, youmust first use the globalstatement.
The statement global VarName tells Pythonthat VarName is a globalvariable. Pythonstops searching the local
namespace for the variable.
For example, we define a variable Money inthe globalnamespace. Withinthe functionMoney, we assignMoney
a value, therefore Pythonassumes Money as a localvariable. However, we accessed the value of the local
variable Money before setting it, so anUnboundLocalError is the result. Uncommenting the globalstatement
fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The dir( ) Function:
The dir() built-infunctionreturns a sorted list of strings containing the names defined by a module.
The list contains the names of allthe modules, variables and functions that are defined ina module. Following is a
simple example:
#!/usr/bin/python
# Import built-in module math
import math
content = dir(math)
print content;
Whenthe above code is executed, it produces the following result:
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the specialstring variable __name__ is the module's name, and __file__ is the filename fromwhichthe
module was loaded.
The globals() and locals() Functions:
The globals() and locals() functions canbe used to returnthe names inthe globaland localnamespaces
depending onthe locationfromwhere they are called.
If locals() is called fromwithina function, it willreturnallthe names that canbe accessed locally fromthat function.
If globals() is called fromwithina function, it willreturnallthe names that canbe accessed globally fromthat
function.
The returntype of boththese functions is dictionary. Therefore, names canbe extracted using the keys()
function.
The reload() Function:
Whenthe module is imported into a script, the code inthe top-levelportionof a module is executed only once.
Therefore, if youwant to reexecute the top-levelcode ina module, youcanuse the reload() function. The
reload() functionimports a previously imported module again. The syntax of the reload() functionis this:
reload(module_name)
Here, module_name is the name of the module youwant to reload and not the string containing the module name.
For example, to reload hello module, do the following:
reload(hello)
Packages in Python:
A package is a hierarchicalfile directory structure that defines a single Pythonapplicationenvironment that
consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available inPhone directory. This file has following line of source code:
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions withthe same name as above:
Phone/Isdn.py file having functionIsdn()
Phone/G3.py file having functionG3()
Now, create one more file __init__.py inPhone directory:
Phone/__init__.py
To make allof your functions available whenyou've imported Phone, youneed to put explicit import statements in
__init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you've added these lines to __init__.py, youhave allof these classes available whenyou've imported the
Phone package.
#!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
Whenthe above code is executed, it produces the following result:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
Inthe above example, we have takenexample of a single functions ineachfile, but youcankeep multiple functions
inyour files. Youcanalso define different Pythonclasses inthose files and thenyoucancreate your packages out
of those classes.

Mais conteúdo relacionado

Mais procurados

Python Modules
Python ModulesPython Modules
Python ModulesSoba Arjun
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Pythonprimeteacher32
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAMaulik Borsaniya
 
python Function
python Function python Function
python Function Ronak Rathi
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresIntellipaat
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMINGindupps
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 

Mais procurados (20)

Python Modules
Python ModulesPython Modules
Python Modules
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
 
Advance python
Advance pythonAdvance python
Advance python
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Biopython
BiopythonBiopython
Biopython
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
 
python Function
python Function python Function
python Function
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python Closures
 
Day3
Day3Day3
Day3
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Day2
Day2Day2
Day2
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Python functions
Python functionsPython functions
Python functions
 
PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMING
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 

Semelhante a Python modules

Semelhante a Python modules (20)

Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptx
 
Python modules
Python modulesPython modules
Python modules
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdf
 
Python modules
Python   modulesPython   modules
Python modules
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
packages.pptx
packages.pptxpackages.pptx
packages.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
What's New In Python 2.5
What's New In Python 2.5What's New In Python 2.5
What's New In Python 2.5
 
Python for Beginners
Python  for BeginnersPython  for Beginners
Python for Beginners
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programming
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Python Programming - Functions and Modules
Python Programming - Functions and ModulesPython Programming - Functions and Modules
Python Programming - Functions and Modules
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Introduction to python programming 2
Introduction to python programming   2Introduction to python programming   2
Introduction to python programming 2
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Chapter - 4.pptx
Chapter - 4.pptxChapter - 4.pptx
Chapter - 4.pptx
 

Mais de Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai

Mais de Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai (20)

Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_SimulationVLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
 
Question Bank: Network Management in Telecommunication
Question Bank: Network Management in TelecommunicationQuestion Bank: Network Management in Telecommunication
Question Bank: Network Management in Telecommunication
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdfINTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
 
LRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdfLRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdf
 
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdfNetwork Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
 
Euler Method Details
Euler Method Details Euler Method Details
Euler Method Details
 
Mini Project fo BE Engineering students
Mini Project fo BE Engineering  students  Mini Project fo BE Engineering  students
Mini Project fo BE Engineering students
 
Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students
 
Ballistics Detsils
Ballistics Detsils Ballistics Detsils
Ballistics Detsils
 
VLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant GohatreVLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant Gohatre
 
Cryptography and Network Security
Cryptography and Network SecurityCryptography and Network Security
Cryptography and Network Security
 
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...
 
Python overview
Python overviewPython overview
Python overview
 
Python numbers
Python numbersPython numbers
Python numbers
 
Python networking
Python networkingPython networking
Python networking
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Python loops
Python loopsPython loops
Python loops
 

Último

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 

Último (20)

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 

Python modules

  • 1. http://www.tutorialspoint.com/python/python_modules.htm Copyright © tutorialspoint.com PYTHON MODULES A module allows youto logically organize your Pythoncode. Grouping related code into a module makes the code easier to understand and use. A module is a Pythonobject witharbitrarily named attributes that youcanbind and reference. Simply, a module is a file consisting of Pythoncode. A module candefine functions, classes and variables. A module canalso include runnable code. Example: The Pythoncode for a module named aname normally resides ina file named aname.py. Here's anexample of a simple module, support.py def print_func( par ): print "Hello : ", par return The import Statement: Youcanuse any Pythonsource file as a module by executing animport statement insome other Pythonsource file. The import has the following syntax: import module1[, module2[,... moduleN] Whenthe interpreter encounters animport statement, it imports the module if the module is present inthe search path. A searchpathis a list of directories that the interpreter searches before importing a module. For example, to import the module hello.py, youneed to put the following command at the top of the script: #!/usr/bin/python # Import module support import support # Now you can call defined function that module as follows support.print_func("Zara") Whenthe above code is executed, it produces the following result: Hello : Zara A module is loaded only once, regardless of the number of times it is imported. This prevents the module executionfromhappening over and over againif multiple imports occur. The from...import Statement Python's from statement lets youimport specific attributes froma module into the current namespace. The from...import has the following syntax: from modname import name1[, name2[, ... nameN]] For example, to import the functionfibonaccifromthe module fib, use the following statement: from fib import fibonacci This statement does not import the entire module fib into the current namespace; it just introduces the item fibonaccifromthe module fib into the globalsymboltable of the importing module. The from...import * Statement:
  • 2. It is also possible to import allnames froma module into the current namespace by using the following import statement: from modname import * This provides aneasy way to import allthe items froma module into the current namespace; however, this statement should be used sparingly. Locating Modules: Whenyouimport a module, the Pythoninterpreter searches for the module inthe following sequences: The current directory. If the module isn't found, Pythonthensearches eachdirectory inthe shellvariable PYTHONPATH. If allelse fails, Pythonchecks the default path. OnUNIX, this default pathis normally /usr/local/lib/python/. The module searchpathis stored inthe systemmodule sys as the sys.path variable. The sys.pathvariable contains the current directory, PYTHONPATH, and the installation-dependent default. The PYTHONPATH Variable: The PYTHONPATH is anenvironment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shellvariable PATH. Here is a typicalPYTHONPATH froma Windows system: set PYTHONPATH=c:python20lib; And here is a typicalPYTHONPATH froma UNIX system: set PYTHONPATH=/usr/local/lib/python Namespaces and Scoping: Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). A Pythonstatement canaccess variables ina local namespace and inthe global namespace. If a localand a global variable have the same name, the localvariable shadows the globalvariable. Eachfunctionhas its ownlocalnamespace. Class methods follow the same scoping rule as ordinary functions. Pythonmakes educated guesses onwhether variables are localor global. It assumes that any variable assigned a value ina functionis local. Therefore, inorder to assigna value to a globalvariable withina function, youmust first use the globalstatement. The statement global VarName tells Pythonthat VarName is a globalvariable. Pythonstops searching the local namespace for the variable. For example, we define a variable Money inthe globalnamespace. Withinthe functionMoney, we assignMoney a value, therefore Pythonassumes Money as a localvariable. However, we accessed the value of the local variable Money before setting it, so anUnboundLocalError is the result. Uncommenting the globalstatement fixes the problem. #!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money
  • 3. Money = Money + 1 print Money AddMoney() print Money The dir( ) Function: The dir() built-infunctionreturns a sorted list of strings containing the names defined by a module. The list contains the names of allthe modules, variables and functions that are defined ina module. Following is a simple example: #!/usr/bin/python # Import built-in module math import math content = dir(math) print content; Whenthe above code is executed, it produces the following result: ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] Here, the specialstring variable __name__ is the module's name, and __file__ is the filename fromwhichthe module was loaded. The globals() and locals() Functions: The globals() and locals() functions canbe used to returnthe names inthe globaland localnamespaces depending onthe locationfromwhere they are called. If locals() is called fromwithina function, it willreturnallthe names that canbe accessed locally fromthat function. If globals() is called fromwithina function, it willreturnallthe names that canbe accessed globally fromthat function. The returntype of boththese functions is dictionary. Therefore, names canbe extracted using the keys() function. The reload() Function: Whenthe module is imported into a script, the code inthe top-levelportionof a module is executed only once. Therefore, if youwant to reexecute the top-levelcode ina module, youcanuse the reload() function. The reload() functionimports a previously imported module again. The syntax of the reload() functionis this: reload(module_name) Here, module_name is the name of the module youwant to reload and not the string containing the module name. For example, to reload hello module, do the following: reload(hello) Packages in Python: A package is a hierarchicalfile directory structure that defines a single Pythonapplicationenvironment that consists of modules and subpackages and sub-subpackages, and so on.
  • 4. Consider a file Pots.py available inPhone directory. This file has following line of source code: #!/usr/bin/python def Pots(): print "I'm Pots Phone" Similar way, we have another two files having different functions withthe same name as above: Phone/Isdn.py file having functionIsdn() Phone/G3.py file having functionG3() Now, create one more file __init__.py inPhone directory: Phone/__init__.py To make allof your functions available whenyou've imported Phone, youneed to put explicit import statements in __init__.py as follows: from Pots import Pots from Isdn import Isdn from G3 import G3 After you've added these lines to __init__.py, youhave allof these classes available whenyou've imported the Phone package. #!/usr/bin/python # Now import your Phone Package. import Phone Phone.Pots() Phone.Isdn() Phone.G3() Whenthe above code is executed, it produces the following result: I'm Pots Phone I'm 3G Phone I'm ISDN Phone Inthe above example, we have takenexample of a single functions ineachfile, but youcankeep multiple functions inyour files. Youcanalso define different Pythonclasses inthose files and thenyoucancreate your packages out of those classes.