作者sandwichC (没回应=挂站)
看板Translate-CS
标题Fw: [翻译] Google 建议的 Python 风格指南 5
时间Mon Apr 29 22:09:15 2013
※ [本文转录自 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 层级的函数
存取之。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 75.102.68.144
※ 发信站: 批踢踢实业坊(ptt.cc)
※ 转录者: sandwichC (75.102.68.144), 时间: 04/29/2013 22:09:15