目录
一、导入模块
# 将之保存到文件 Test1.py 中
>>> def c2f(cel):
... fah = cel * 1.8 + 32
... return fah
>>> def f2c(fah):
... cel = (fah - 32) / 1.8
... return cel
# (1)import 模块名
# 将之保存到文件 Test2.py 中
>>> import Test1
>>> print("32摄氏度 = %.2f 华氏度" % c2f(cel))
>>> print("99摄氏度 = %.2f 华氏度" % f2c(fah))
# (2)from 模块名 import 函数名
# 将之保存到文件 Test3.py 中
>>> from import c2f, f2c # 不建议直接采用 from Test1.py import *,防止命名冲突
>>> print("32摄氏度 = %.2f 华氏度" % c2f(cel))
>>> print("99摄氏度 = %.2f 华氏度" % f2c(fah))
# (3)import 模块名 as 新名字
# 将之保存到文件 Test4.py 中
>>> import Test1 as t1
>>> print("32摄氏度 = %.2f 华氏度" % t1.c2f(cel))
>>> print("99摄氏度 = %.2f 华氏度" % t2.f2c(fah))
二、__name__ == '__main__'
# 将文件保存到 TestTest.py 中
>>> def c2f(cel):
... fah = cel * 1.8 + 32
... return fah
>>> def f2c(fah):
... cel = (fah - 32) / 1.8
... return cel
>>> def tt:
... print("32摄氏度 = %.2f 华氏度" % c2f(cel))
... print("99摄氏度 = %.2f 华氏度" % f2c(fah))
... # 保证只有单独运行 TestTest.py 时才执行 test() 函数
... # 其他文件调用该模块时,不会执行下面的 test() 函数
>>> if __name__ == '__main__':
... test()
三、搜索路径
Python 的模块导入需要进行路径搜索,若导入指定模块则需先在预定义好的路径中进行搜索,若在该路径下未找到指定文件则报错。
# 通过该方法可查看预设定路径,返回的路径为一个目录
>>> import sys
>>> sus.path
['', 'E:\\Python_3.9.0\\Lib\\idlelib', 'E:\\Python_3.9.0\\python39.zip', 'E:\\Python_3.9.0\\DLLs', 'E:\\Python_3.9.0\\lib', 'E:\\Python_3.9.0', 'E:\\Python_3.9.0\\lib\\site-packages']
# site-packages 为最佳选择
# 搜索路径找不到指定模块,则可将指定模块所在路径添加到搜索路径中
>>> import sys
>>> sys.path.append("E:\\Test")
>>> sys.path
['', 'E:\\Python_3.9.0\\Lib\\idlelib', 'E:\\Python_3.9.0\\python39.zip', 'E:\\Python_3.9.0\\DLLs', 'E:\\Python_3.9.0\\lib', 'E:\\Python_3.9.0', 'E:\\Python_3.9.0\\lib\\site-packages', 'E:\\Test']
四、包
通常会将模块分门别类的放在不同的文件夹,然后把不同文件夹的位置添加到搜索路径中。
包的实现为:(1)创建存放模块的文件夹,文件夹名字就是包的名字
(2)在文件夹中创建一个 __init__.py 的模块文件,内容可为空
(3)将相关模块放入文件夹
(注:Pycharm中直接在Project中右键new--python package,文件夹中默认建立__init__.py文件,在文件中加入 __all__ = ['模块名1', '模块名2', ...] ,其中模块名为该python package下的 .py 模块文件名,需要在某个文件中引入时,import 模块名即可)
# 先保证将模块文件 test.py 放入 Test 文件夹中
# 然后再引入模块
>>> import Test.test as tt


被折叠的 条评论
为什么被折叠?



