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