python中package机制的两种实现方式
当执行import
module时,解释器会根据下面的搜索路径,搜索module1.py文件。
1) 当前工作目录
2) PYTHONPATH中的目录
3) Python安装目录
(/usr/local/lib/python)
事实上,模块搜索是在保存在sys.path这个全局变量中的目录列表中进行搜索。
sys.path会在解释器开始执行时被初始化成包含:
1)当前工作目录
2) PYTHONPATH中的目录
3) Python安装目录
(/usr/local/lib/python)
package是模块的集合,每一个Package的根目录下面都应当有一个__init__.py
文件。当解释器发现目录下有这个文件时,他就会认为这是一个Package,而不是一个普通的目录。
我们通过下面这样的一个实例来说明
假定项目结构如下:
demo.py
MyPackage
---classOne.py
---classTwo.py
---__init__.py 现在我们通过两种方式来实现包机制,主要区别就在于是否在__init__.py中写入模块导入语句。
1,__init__.py是一个空白文件的方式, demo.py内容如下:
from MyPackage.classOne import classOne
from MyPackage.classTwo import classTwo
if __name__ == "__main__":
c1 = classOne()
c1.printInfo()
c2 = classTwo()
c2.printInfo()
classOne.py内容如下:
class classOne:
def __init__(self):
self.name = "class one"
def printInfo(self):
print("i am class One!")
classTwo.py内容如下:
class classTwo:
def __init__(self):
self.name = "class two"
def printInfo(self):
print("i am class two!")
2,如果在__init__.py中写入导入模块的语句,则上述例子可以这样来做。
其中__init__.py
相关文档:
Install Python Eric IDE
1 Download following things
1) Python3.1
2) PyQt for python 3.1
(http://www.riverbankcomputing.co.uk/software/pyqt/download) I am using
PyQt-Py3.1-gpl-4.7.3-2.exe
3) Eric5 IDE
(http://eric-ide.python-projects.org/eric-download.html)
2 ......
队列:
与堆栈类似,通过python的列表类型来实现,参考 help(list)
shoplist=['apple','mango','carrot','banana']
print 'I have',len(shoplist),'items to purchase'
print 'these items are:'
for item in shoplist:
print item,
shoplist.append('rice')
print 'my shopping list is now', shoplist
shoplist. ......
#from pp3e Chapter 9.3
#############################################################################
# popup three new window, with style
# destroy() kills one window, quit() kills all windows and app; top-level
# windows have title, icon, iconify/deiconify and protocol for wm events;
# there ......
英文版Dive in python可以在下面找到中文翻译http://linuxtoy.org/docs/dip/toc/index.html
模块的__name__,当模块被import时,其为模块的名字,当模块作为main执行的时候,其为__main__
词典的key是大小写敏感的。
List也支持重载+操作,用于将两个list连接起来,并返回一个List,因此它没有extended执行高效。list也+ ......