模块是包含Python定义和语句的文件。一个模块可以定义函数,类和变量。模块也可以包含可运行的代码。将相关代码分组到一个模块中可使代码更易于理解和使用。
示例:
# A simple module, calc.py def add(x, y): return (x+y) def subtract(x, y): return (x-y)
import语句
通过在其他一些Python源文件中执行import语句,我们可以将任何Python源文件用作模块。
当解释器遇到import语句时,如果搜索路径中存在模块,它将导入该模块。搜索路径是解释器搜索以导入模块的目录列表。例如,要导入模块calc.py,我们需要在脚本顶部放置以下命令:
# importing module calc.py import calc print add(10, 2)
输出:
12
from import语句
Python的from语句可让您从模块中导入特定属性。from .. import ..具有以下语法:
# 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)
输出:
4.0720
dir() 函数
内置的dir()函数返回一个包含由模块定义的名称的字符串排序列表。该列表包含模块中定义的所有模块,变量和功能的名称。
# Import built-in module random import random print dir(math)
输出:
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random','_sin', '_sqrt', '_test', '_test_generator', '_urandom','_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits','getstate', 'jumpahead', 'lognormvariate', 'normalvariate','paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
说明python内置模块的代码段:
# 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 degreees 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 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)
输出:
5.03.14159265359114.5915590261.04719755120.9092974268260.877582561890.2341433623512430.40153317295188.4917616788True1461425771.871970-01-06