Python模块
Python模块是包含Python定义和语句的文件。模块可以定义函数、类和变量。模块还可以包含可运行代码。将相关代码分组到一个模块中,使代码更易于理解和使用。它还使代码在逻辑上组织起来。
示例:创建一个简单的模块
Python3
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Python3
# importing module calc.py
import calc
print(calc.add(10, 2))
Python3
# 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))
Python3
# 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))
Python3
# importing sys module
import sys
# importing sys.path
print(sys.path)
Python3
# importing sqrt() and factorial from the
# module math
import math as gfg
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(gfg.sqrt(16))
print(gfg.factorial(6))
Python3
# Import built-in module random
import random
print(dir(random))
Python3
# 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)
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))
Python中的导入模块——导入语句
我们可以使用其他Python源文件中的import 语句将模块中定义的函数、类导入另一个模块。
句法:
import module
当解释器遇到 import 语句时,如果模块存在于搜索路径中,它会导入该模块。搜索路径是解释器搜索导入模块的目录列表。例如,要导入模块 calc.py,我们需要将以下命令放在脚本顶部。
注意:这不会直接导入函数或类,而是仅导入模块。要访问模块内的函数,请使用点 (.)运算符。
示例:在Python中导入模块
Python3
# importing module calc.py
import calc
print(calc.add(10, 2))
输出:
12
从导入 陈述
Python 的from语句允许您从模块导入特定属性,而无需将模块作为一个整体导入。
示例:从模块导入特定属性
Python3
# 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.0
720
导入所有名称 - 从导入 * 声明
与 from import 语句一起使用的 * 符号用于将模块中的所有名称导入当前命名空间。
句法:
from module_name import *
* 的使用有其优点和缺点。如果您确切知道模块需要什么,则不建议使用 *,否则请使用。
示例:导入所有名称
Python3
# 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))
4.0
720
定位模块
每当在Python中导入模块时,解释器都会查找多个位置。首先,它将检查内置模块,如果未找到,则查找 sys.path 中定义的目录列表。 Python解释器以下列方式搜索模块 -
- 首先,它在当前目录中搜索模块。
- 如果在当前目录中找不到该模块, Python会在 shell 变量 PYTHONPATH 中搜索每个目录。 PYTHONPATH 是一个环境变量,由目录列表组成。
- 如果这也失败了, Python会检查安装Python时配置的依赖于安装的目录列表。
示例:模块的目录列表
Python3
# importing sys module
import sys
# importing sys.path
print(sys.path)
输出:
[‘/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’]
导入和重命名模块
我们可以在使用 as 关键字导入模块时重命名模块。
示例:重命名模块
Python3
# importing sqrt() and factorial from the
# module math
import math as gfg
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(gfg.sqrt(16))
print(gfg.factorial(6))
4.0
720
dir()函数
dir() 内置函数返回一个排序的字符串列表,其中包含模块定义的名称。该列表包含在模块中定义的所有模块、变量和函数的名称。
Python3
# Import built-in module random
import random
print(dir(random))
输出:
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’, ‘TWOPI’, ‘_BuiltinMethodType’, ‘_MethodType’, ‘_Sequence’, ‘_Set’, ‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘_acos’, ‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_inst’, ‘_itertools’, ‘_log’, ‘_pi’, ‘_random’, ‘_sha512’, ‘_sin’, ‘_sqrt’, ‘_test’, ‘_test_generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’, ‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’, ‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]
说明Python内置模块的代码片段:
Python3
# 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)
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.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
1970-01-06