Module与包 #
Module #
定义模块 #
Python 中一个文件就是一个模块。
utils.py
print('load module')
COUNT = 10
class StrUtils:
COUNT = 20
@staticmethod
def sort_words(words):
return sorted(words)
@staticmethod
def echo():
print(COUNT, StrUtils.COUNT)
@classmethod
def cout(cls):
print(cls)
print(COUNT, StrUtils.COUNT)
import #
import 用于导入模块,共有以下三种方式
第一种
import utils
utils.StrUtils.echo() # 10 20
utils.StrUtils.cout() # 10 20
print(utils.StrUtils.COUNT) # 20
print(utils.COUNT) # 10
第二种
from utils import StrUtils
sentents = ['z', 'b', 'e', 'p']
print(StrUtils.sort_words(sentents))
第三种
import utils as helper
print(helper.COUNT)
模块路径 #
Python 搜索模块的路径是存放在 sys 中的,可以调用以下方法进行打印。
import sys
print(sys.path)
__name__
可以用于判断当前是否是主程序还是引入的模块。
print(__name__) # __main__
print(helper.__name__) # utils
通过进行判断我们可以直接将测试程序写在模块中,只有直接运行模块时才会运行测试。
if __name__ == '__main__':
StrUtils.echo()
包 #
Python 中包是模块的集合,一个包就是一个包含 __init__.py
文件的目录,文件内容可以为空。
例
在 foopkg 包下含有 __init__.py
和 calculator.py
两个文件。
from foopkg.calculator import add
print(add(3, 4))