1.模塊的__name__屬性
1 #!/usr/bin/python
2 # Filename: using_name.py
3
4 if __name__ == '__main__':
5 print 'This program is being run by itself'
6 else:
7 print 'I am being imported from another module'
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>
如果__name__是'__main__',這說明這個模塊被用戶單獨運行,這樣,可以根據當前這個模塊是否正在被別的模塊引用,決定是否執行代碼塊。
2.使用dir()函數來列出模塊的標示符
可以使用內建的dir函數來列出模塊定義的標識符。標識符有函數、類和變量。
當你為dir()提供一個模塊名的時候,它返回模塊定義的名稱列表。如果不提供參數,它返回當前模塊中定義的名稱列表。
同時,可以使用del函數來刪除當前模塊中的變量/屬性。