(以下基本摘自《王純業的python學習筆記》,所有命令均測試通過)
>>> sys.path
['C:/Python26/code', 'C:\\Python26\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\Pythonwin', 'C:\\Python26\\lib\\site-packages\\wx-2.8-msw-unicode']
>>> import xxx
Traceback (most recent call last):
ImportError: No module named xxx
sys.path.append(‘相對路徑或者絕對路徑’)
"""
this only is a very simple test module
"""
age=0 # a simple attribute
def sayHello(): # a simple function in a module
if __name__=="__main__":
>>> import test_module
>>> test_module.age
0
>>> test_module.sayHello()
Hello
>>>
>>> from test_module import age,sayHello
>>> age
0
>>> sayHello
<function sayHello at 0x012DF430>
>>> sayHello()
Hello
>>> test_module
Traceback (most recent call last):
NameError: name 'test_module' is not defined
>>>
Python中有很多name space,常用的有:build—in name space(內建命名空間)global name space(全局命名空間),local name space(局部命名空間)。在不同的name space中的name是沒有關係的。
每個object都有自己的name space,可以通過object.name的方式訪問object的name space中的name,每個object的name都是獨立。即使在別的name space中有與之相同的name,它們也是沒有任何關聯的。
每一個object,都有自己的name space,name space都是動態創建的,每一個name space的生存時間也不一樣。
If _name_= = “_main_”:
>>> import sys
>>> sys.path.append('C:\Python26\code')
>>> sys.path
['C:\\Python26\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\Pythonwin', 'C:\\Python26\\lib\\site-packages\\wx-2.8-msw-unicode', 'C:\\Python26\\code']
>>> import test_module
>>> dir(test_module)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'age', 'sayHello']
>>> test_module.__name__
'test_module'
>>>
LGB的規則用scope的概念來解釋就是:和任何代碼執行的時候,都至少有三個scope:local name space,global name space ,buildin name space (LGB)。看下面的例子:
>>> def sayHello():
>>> saidHello=sayHello
>>> saidHello
<function sayHello at 0x012DFE30>
>>> sayHello
<function sayHello at 0x012DFE30>
>>> sayHello()
Hello
>>> saidHello()
Hello
>>>
用del可以從一個name space刪除一個name,如:
>>> a=1
>>> b=a
>>> a
1
>>> b
1
>>> id(a)
11364056
>>> id(b)
11364056
>>> del a
>>> a
Traceback (most recent call last):
NameError: name 'a' is not defined
>>> b
1