定义:
包:包含__init__.py文件、模块(也是.py文件)
当包被其它模块调用时,首先会执行该包下的__init__文件
包含有模块,包可以有多级
模块的导入:
import
from...import...
当Python导入一个模块时,Python首先查找当前路径;然后查找lib目录、site-packages目录(python\Lib\site-packages)和环境变量PYTHONPATH设置的目录
被调用模块或包路径必须在主文件同级目录或sys.path列出的目录下
>>> import sys
>>> sys.path
['', '/usr/lib/python26.zip', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/site-packages']
包必须至少含有一个__init__.py文件,__init__.py文件内容可以为空,用于标识该目录是包
__init__.py文件还用于提供同一路径下的模块列表,这样可在主文件中一次导入包中的所有模块
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAkMAAADRCAIAAABAaiGtAAAaIUlEQVR4nO3d30/TWf7H8c9f0V4JV643/rix3qhcuMqFTpoYCYnRkM0YE78aQhxC8k2+CVn5TjeG2SbzVVzjbleGWDRGlmUM29EsKPgtiwODMoJbJ2VknbpF6Fg1n+/UgY+Tfi9aSn9Cf5z2cz79PB85F4r1Y/2c0/PqOedNUTQAAIxM0fsJAABQEpIMAGBsJBkAwNhIMgCAsZFkAABjI8kAAMZGkgEAjI0kAwAYG0kGADA2kgwAYGwkGQDA2EgyAICxkWQAAGMjyQAAxkaSAQCMjSQDABgbSQYAMDaSDABgbCQZAMDYSDIAgLGRZAAAYyPJAADGRpIBAIyNJAMAGBtJBgAwNpIMEOmHpbe9D57+/suJ1p77Vd9+/+VE74OnPyy91fuuw+xIMkCYrx59r3u66NK+evS93vcepkaSAWJ4zBpjseYhzKAfkgwQ4Ielt4k5/RO9Q6WSLfk/yzYj9EKSAQL0PnhqwhhL+y/3Pniqdz/ApEgyQACTlHis337/5YTe/QCTIskAAXRPEUma3v0AkyLJAAF0jxBJmt79AJMiyQABdI8QSZre/QCTIskAAXSPEEma3v0AkyLJAAF0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nqbauNzUEBt12xNsYSQ/W7G62JeTzLPZ507ihzyQer/CyEFxDFL9sWv5fFv0FJXKIY5S8gqjYkWbnkn2TajMteqyjWfA7pU5LMfqkvvsNU3+yeSbyFC/U1KYp8c06yWJJlWZElv0nWNE3TAkNO+66m+EaNOulsbHQOBdTEVTJXc6G+ptWpJ48ky3KJ1CRrc69utzU6k2I04x77XXXlvuWs8nMQWkCkaZqmzVyqi71rKaqAKPUSyf+mMQuIDIEkM6rcs1Vo8KSsc86qpGlFDXhdzY1t7j6Xa3UNtmbS2djsnkkJiJDXaa9vHsodGqrXUS9mayYlMVKl3WNx/+Y6WOVnJ7aASNM0v7uxLt6bRRUQpV4iwbAFRIZAkhUjfTFh/+1/5l5VlOmyuZJM9Tp2yTrnJHgdisMbGmyuq2tqdg2uRlVops/RVFffVuq2iqgj85xJlnaPK3REzyo/K8EFRP6+pi2NiaVpUQVEqZdIkKyAqMqQZEaVLckCfY2xvQ5dnlHVyZpk1XuPDbnKF1tA5Hc3pnZt4QVEGZdIkKyAqMqQZID+WOUXSVwBkTrprK9rS9u2LqyAKNslpC0gqjIkGQBNM/IqX0QBUcbfjtcuFlBAlPUS0hYQVRmSDICxUUAEkgyAsVFABJIMAMrPZAVEFUaSAQCMjSQDABgbSQYAMDaSDABgbCQZAMDYSDIAgLGRZAAAYyPJAADGRpIBAIyNJAMAGBtJBgAwtv8HlZFGoOhtiz8AAAAASUVORK5CYII=" alt="" />
接下来自定义包
p1的__init__.py
if __name__ == '__main__':
print ('main')
else:
print ('p1 inited')
p2的__init__.py
if __name__ == '__main__':
print ('main')
else:
print ('p2 inited')
p1的m1.py
def func():
print ('p1.m1.func()') if __name__ == '__main__':
print ('m1.py as main processor')
else:
print ('m1.py is called')
p2的m2.py
def func2():
print ('p2.m2.func2()') if __name__ == '__main__':
print ('m2.py as main processor')
else:
print ('m2.py is called')
main.py
from p1 import m1
from p2 import m2 m1.func()
m2.func()
执行主文件(导入文件会执行__init__.py文件)
[root@hy p]# python main.py
p1 inited
m1 is called
p2 inited
m2 is called
p1.m1.func()
p1.m2.func()