程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Getting started with Python zero basics -6 modules and packages

編輯:Python

6. Modules and packages

modular modules

In the previous program , You may have used something like from math import pi To import variables or functions . This is actually using modular .

modular :Python Save the program in a file , Can run in the interpreter . This file is modular .

The statements in the module can Import (import) To other Python In the program .

Using modular benefits : modularization , Each module writes related functions ; Avoid file length and confusion .

Create a module

Create a new file ( The file named Module name .py), Write a program in a file .

for instance : Create a triangle related module :

New file tri_f.py, And then write in :

import math
print("tri_f modular Start ")
def edge_length(a, b, c):
""" Returns the sum of the lengths of the three sides """
return a + b + c
def area(a, b, c):
""" Returns the area of the triangle """
p = (a + b + c) / 2
s = math.sqrt(p * (p - a) * (p - b) * (p - c))
return s
print("tri_f modular end ")

Then save (Ctrl+s). Then the module is created .

Using modules

Using the module through import Statement to import variable definitions in the module 、 Functions and other executable statements .

example , Using modules tri.f.

stay tri_f.py At the same directory Create test.py.

Be careful : If it is not a peer Directory , The interpreter will not find , Need to be in sys.path Add search path to , Such as

import sys sys.path.append(r'D:\PY_TEST\pythonProject\6modules') # Replace it with your own directory

a, b, c = 3, 4, 5
# Import a specific function from a module
from tri_f import area # from tri_f Module import function area The definition of
print(area(a, b, c)) # Then you can use the function area, Calculate the area of the triangle
# The import module
import tri_f # Import tri_f modular
print(tri_f.area(a, b, c)) # The module name should be added in front of the function
# Alias the module
import tri_f as tr
print(tr.area(a, b, c))
# ( Not recommended ) Import all functions from the module (_ Except for the functions that begin with )
from tri_f import *
print(area(a, b, c))
print(edge_length(a, b, c))

function test.py We get the following results :

tri_f modular Start
tri_f modular end
6.0
6.0
6.0
6.0
12.0

adopt import modular , We not only import functions , It also executes the statements in the module .

To sum up ,Import Usage of :

# Import a specific function from a module
from modular import function
# The import module
import modular
# Alias the module
import modular as Alias
# ( Not recommended ) Import all functions from the module (_ Except for the functions that begin with ) And variables
from modular import *

Module name __name__

You may have seen it The following statement :

 if __name__ == '__main__':
print('hello')

there __name__ It is actually the name of the module . When the module is imported ,__name__ Is the file name of the module . When this module runs as the main program , Modular __name__ It will be assigned to '__main__'.

import math
print('name=',__name__)
def edge_length(a, b, c):
""" Returns the sum of the lengths of the three sides """
return a + b + c
def area(a, b, c):
""" Returns the area of the triangle """
p = (a + b + c) / 2
s = math.sqrt(p * (p - a) * (p - b) * (p - c))
return s
if __name__ == '__main__':
print(area(3, 4, 5))
print('hello')

function tri_f.py, Output :

name= __main__
6.0
hello

function test.py when ,tri_f Medium __name__ It will become the module name tri_f, So it won't execute tri.f Module if Contents of Li :

if __name__ == '__main__':
print(area(3, 4, 5))
print('hello')

Module details

import Statement what happens when you import a module :

In the execution module sentence ( Including defining functions, etc ).

Be careful :

! Module sentence Used to initialize the module , And only in import sentence   for the first time   Execute... When the module name is encountered ( Prevent duplication ).

! We need to pay attention to , If there are more than one identical Of function name , The last defined function will replace the previous Function with the same name to Cover fall .

! You can use the same notation as accessing module functions , Access the global variables of the module ,modname.itemname.

The module has its own Private symbol table , Used as a All functions in the module Of Global symbol table . therefore , Global variables in the module will not conflict with user-defined global variables .( Don't get tangled up , Namespaces are described in detail in Chapter 9 )

package package

Create a package

A package is a folder containing modules , The folder must contain  __init__.py  file .

In the simplest case ,__init__.py  Just an empty file , But this file can also execute the initialization code of the package , Or set  __all__  Variable , See below ( Import... From package *).

sound/ # Top package
__init__.py # initialization
formats/ # subpackage , Used to format sound
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ # subpackage , For sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ # subpackage , Used for filtration
__init__.py
equalizer.py
vocoder.py
karaoke.py
...

Use the bag

Importing from a package is very similar to importing from a module .

  • You can import a single module from a package , for example :

import sound.effects.echo

This code loads sub modules  sound.effects.echo , However, the full name of the sub module must be used when referencing :

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

  • ( recommend ) Another import Sub module Approach is to :

from sound.effects import echo

This code can also load sub modules  echo , No package prefix You can also use :

echo.echofilter(input, output, delay=0.7, atten=4)

  • Import Another variant of the statement is to directly import the required function or variable :

from sound.effects.echo import echofilter

Again , This will also load the sub modules  echo, But you can use functions directly  echofilter()

echofilter(input, output, delay=0.7, atten=4)

Be careful , Use  from package import item  when ,item It can be a sub module of a package ( Or a subpack ), It can also be defined in the package function 、 Class or variable Other names .

first Find the... Defined in the package function 、 Class or variable etc. , If not found, assume item It's a module , And try to load the module . If you still can't find item, The trigger  ImportError  abnormal .

contrary , Use  import item.subitem.subsubitem  Syntax , Except for the last item , Every item All have to be bags ; The last item can be Module or package , But it cannot be the class defined in the previous item 、 Function or variable .

Import... From package *

Similar module import *, Use  from sound.effects import *  when , This statement should import all the sub modules of the package . But this can lead to too many things , Waste time and cause conflict . therefore , Use  from sound.effects import * Will only import in __init__.py in __all__ Modules in variables .

__all__ = ["echo", "surround", "reverse"]

Relative Import

You can also use when a package contains multiple subpackages import Of the statement  from module import name  Perform relative import as . These import statements use leading periods to represent the current package and parent package in the relative import . for example , be relative to  effect Under bag surround  modular , have access to :

from . import echo
from .. import formats
from ..filters import equalizer

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved