Fw: [翻譯] Google 建議的 Python 風格指南 5

作者: sandwichC ( )   2013-04-29 22:09:15
※ [本文轉錄自 Python 看板 #1HVdwu1f ]
作者: sandwichC (沒回應=掛站) 看板: Python
標題: [翻譯] Google 建議的 Python 風格指南 5
時間: Mon Apr 29 22:07:50 2013
原文網址:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
* Global variables
避免使用全域變數。
釋義:
global variable 指被宣告在 module 等級的變數。
優點:
有時候很方便。
缺點:
因為在 import 時會對 module level 的變數賦值,因此 import 時可能會改變模
組的行為。
編案:我並不很確定這句話要表達的涵義,原文如下:
Cons: Has the potential to change module behavior during the import,
because assignments to module-level variables are done when the
module is imported.
我自己的解釋如下,但並不一定正確代表原文要傳達的訊息:
假設有三個檔案:
File 1: foo.py
x = 1
File 2 bar.py
import foo
foo.x = 2
def func():
pass
File 3: main.py
import foo
foo.x = 3
import bar
bar.func()
print foo.x
如果只看 main.py,會很疑惑為何輸出值是2,這是因為當 main.py 在 import bar
時,bar.py 的第二行對 foo.x 賦值了。
如果版友很更好的見解歡迎提出討論。
決策:
避免使用全域變數,必要時可考慮用 class 變數。可能需要用到全域變數的狀況:
1. 腳本預設的選項。
2. 模組層級的常數。如:PI = 3.14159。常數的命名應該只包含大寫字母和底線,
關於命名的細節在之後命名的規則會有更詳細的說明。
3. 有時候使用全域變數來當快取或當作函數的返回值很方便。
4. 若真需要全域變數,該變數應只在 module 內使用,並透過 module 層級的函數
存取之。

Links booklink

Contact Us: admin [ a t ] ucptt.com