python_day8.2

一:模块
命名空间

>>> import test
>>> hi()
Traceback (most recent call last):
  File "<pyshell#218>", line 1, in <module>
    hi()
NameError: name 'hi' is not defined
>>> test.hi()
hi
View Code

导入模块
第一种:import模块名
第二种:from 模块名 import函数名
第三种:import 模块名 as 新名字

>>> import test
>>> hi()
Traceback (most recent call last):
  File "<pyshell#218>", line 1, in <module>
    hi()
NameError: name 'hi' is not defined
>>> test.hi()
hi
>>> from test import hi
>>> hi()
hi
>>> import test as t
>>> t.hi()
hi
View Code

模块的自己测试;

在一个模块中有如下代码:(摄氏度和华氏度的转换)

def c2f(cel):
    fah=cel*1.8+32
    return fah
def f2c(fah):
    cel=(fah-32)/1.8
    return cel
def test():
    print('测试,0摄氏度=%.2f华氏度' % c2f(0))
    print('测试,0华氏度=%.2f摄氏度' % f2c(0))
test()

在调用时,会直接执行test函数,为了不在导入模块是调用test函数,应该修改为:

if __name__ =='__main__':
    test()

搜索路径:
如果要导入的模块和IDLE不在一个目录之下
import sys
sys.path.append('地址')
地址中的\要改为\\转义字符
包:
package
1.创建一个文件夹,用于存放相关的模块,文件夹的名字就是包的名字
2.在文件夹中创建一个__init__.py的模块文件,内容可以为空(为了声明这个文件夹是一个包)
3.将相关的模块放入文件夹中
导入方法为import 包名.模块名
二:爬虫






猜你喜欢

转载自www.cnblogs.com/wwq1204/p/10719223.html
8.2