Python学习笔记5:模块
这篇博文是之前的博文《python学习之模块》的整理和重发,以和目前发的Python学习笔记成一个系列。
模块
基本概念
在python中,模块是相对于命令行执行的一个概念。如果我们抛开IDE,在cmd下调用python并使用命令行执行命令,就会存在一个问题,前边命令创建的变量在后续执行中无法保存和使用。而模块就是为此存在,简单的说模块就是一组变量、函数、类的集合,到这里我们就可以发现,其实单个的python源代码文件就是一个模块。
#test.py
def test():
print("this is a module test")
a=test
a()
print(dir())
print(__name__)
输出
this is a module test
[’__annotations__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘a’, ‘test’]
__main__
上边代码中dir()
的作用是输出当前已注册的命名,可以简单的理解为当前可以使用的变量、函数、类等。__name__
是当前的模块名,如果__name__="__main__“
则表示当前模块是这次执行的入口,也就是说这次是由python程序直接执行test.py
,而非其它模块引用。
模块引用
当然,一个模块是可以引入另一个模块的,我们可以在同目录下创建另一个模块:
#test2.py
print("this is module test2")
def test2Function():
print("this is a function in module test2")
print("this is test2 module name:"+__name__)
我们可以使用import moduleName
的方式引入test2模块:
#test.py
import test2
def test():
print("this is a module test")
a=test
a()
print(dir())
print(__name__)
test2.test2Function()
输出
this is module test2
this is test2 module name:test2
this is a module test
[’__annotations__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘