方法1(全局变量):为函数的Python最佳实践
id_constant = 1000
id_cnt = 1
def give_id():
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
方法2(FUC变种而不是全局变量):
id_cnt = 1
def give_id():
id_constant = 1000
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
方法3(通过在全局变量):
id_cnt = 1
id_constant = 1000
def give_id(constant, cnt):
return constant * cnt
global id_cnt
id_cnt +=1
id = give_id(id_constant, id_cnt)
即时通讯不确定是否有任何一般的经验法则,但是被广泛接受的函数来访问一个函数内的全局变量重刑?或者如果变量只用于一个函数,那么它应该是一个函数变量的一部分吗?
有时是必要的,但总的来说,在所有的语言,访问'global'变量是不好的做法 – Scironic
一般较少的全局变量意味着更好的代码,所以尝试使用参数并返回值而不是全局变量。什么来问你的问题,上下文将有助于为你选择最好的方法。你在用什么ID? –
不要忘记你可以在函数参数中使用默认值,例如:'def foo(bar = 4):\ print bar',如果调用为'foo()',将会打印'4'。通常这对于很少更改的配置变量来说更好,因为它避免了全局变量(实际上是模块级别的变量),并且保持常量接近代码中的使用。 – thirtythreeforty