Python学习笔记5:模块

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__’, ‘

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值