ch2-3:模块的使用-window环境

导入模块:import 模块名

完成如下工作:

1、编写一个小程序testmodule.py,导入新建的模块nester,并定义一个小列表cast,然后使用调用模块中的函数打印列表到屏幕上;

import nester
cast=['palin','cleese','idle','jones']
print_list(cast)

 2、用idle的编辑窗口打开,并按F5运行:

>>> 
================ RESTART: D:workspaceeclipse	estmodule.py ================
Traceback (most recent call last):
  File "D:workspaceeclipse	estmodule.py", line 3, in <module>
    print_list(cast)
NameError: name 'print_list' is not defined
>>> 

 产生了错误,没有找到函数print_list。

3、python的模块实现命名空间

  python中所有代码都与一个命名空间关联。

  主python程序中(以及IDLE shell中)的代码与一个名为__main__的命名空间关联;

  将代码放在其单独的模块中时,python会自动创建一个与模块名同名的命名空间;

  命名空间就像人的姓氏,如果想指示某个模块命名空间中的某个函数,需要用该模块的命名空间名对这个函数的调用作出限定。

命名空间限定格式:模块名.函数名(参数)

所以修改小程序testmodule.py:

import nester
cast=['palin','cleese','idle','jones']
nester.print_list(cast)

再次按F5允许该程序:

>>> 
================ RESTART: D:workspaceeclipse	estmodule.py ================
palin
cleese
idle
jones
>>> 

 调用成功!!

另外一种调用的方法为:特定导入

from nester import print_list
cast=['palin','cleese','idle','jones']
print_list(cast)

 允许程序:

>>> 
================ RESTART: D:workspaceeclipse	estmodule.py ================
palin
cleese
idle
jones
>>> 

 该方法需注意:

如果当前的命名空间中已经定义了一个名为print_list的函数,这个特定的import语句会用导入的函数覆盖你自定义的函数;

 现在可以把模块上传到PyPI了。

原文地址:https://www.cnblogs.com/apple2016/p/5268508.html