热线电话:13121318867

登录
2019-01-07 阅读量: 625
Python模块

模块是包含Python定义和语句的文件。模块可以定义函数,类和变量。模块还可以包括可运行代码。将相关代码分组到模块中使代码更易于理解和使用。
例:

# A simple module, calc.py

def add(x, y):

return (x+y)

def subtract(x, y):

return (x-y)

导入语句

我们可以通过一些其他的Python源文件执行import语句使用任何Python源文件作为一个模块。

当解释器遇到import语句时,如果模块存在于搜索路径中,它将导入模块。搜索路径是解释器搜索导入模块的目录列表。例如,要导入模块calc.py,我们需要将以下命令放在脚本的顶部:

# importing module calc.py

import calc

print add(10, 2)

进口声明

Python的from语句允许您从模块导入特定属性。在从..进口..语法如下:

# 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)

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子