Python中的常量?
我在很多函数里声明了以下变量,因为我在每个函数里都需要用到这些值。有没有办法让我把它们声明为全局变量,这样我就不用在每个方法里都声明一遍?我在我的一个类的实例方法中使用这些方法。
x = 0
y = 1
t = 2
在C#中,我可以把它们声明为全局类变量,但问题是我不想总是用self.x、self.y和self.z来使用它们,这样会让我的算法代码看起来更乱。我该怎么做呢?
一个典型的用法是:
def _GetStateFromAction(self, state, action):
x = 0
y = 1
t = 2
if (action == 0):
return (state[x], state[y] - 1, state[t])
if (action == 1):
return (state[x] - 1, state[y], state[t])
6 个回答
1
你可以直接在模块的最上面,也就是.py
文件的顶层,声明这些变量,这样就不需要用到self
或者其他类似的东西了。在这种情况下,通常的做法是给这些变量起个大写的名字。
顺便提一下,我想说的是,你可以这样来声明它们:
x, y, t = 0, 1, 2
5
除了使用单独模块的技巧,如果我想把它们放在同一个模块里,我通常会把它们放在一个类里面,就像这样:
class PathConstants(object):
CSIDL_DESKTOP = 0
CSIDL_PROGRAMS = 2
def get_desktop():
return _get_path_buf(PathConstants.CSIDL_DESKTOP)
如果你想让它们更像常量的话,你可以让setattr抛出错误:
class ConstantExeption(Exception):
pass
class ProgramConstants(object):
foo = 10
bar = 13
def __setattr__(self, key, val):
raise ConstantExeption("Cannot change value of %s" % key)
# got to use an instance...
constants = ProgramConstants()
print constants.foo
constants.bar = "spam"
错误追踪信息:
10
Traceback (most recent call last):
File "...", line 14, in <module>
constants.bar = "spam"
File "...", line 9, in __setattr__
raise ConstantExeption("Cannot change value of %s" % key)
__main__.ConstantExeption: Cannot change value of bar
12
如果这些内容都在同一个模块里,那么它们只存在于这个模块的命名空间中,你就不需要担心名字冲突的问题。(而且你仍然可以把它们导入到其他命名空间中)
举个例子:
MyModWithContstants.py
x = 0
y = 0
def someFunc():
dosomethingwithconstants(x,y)
我们还可以这样做:
anotherMod.py
from MyModWithConstants import x
# and also we can do
import MyModWithConstants as MMWC
def somOtherFunc():
dosomethingNew(x, MMWC.y)
## x and MMWC.y both refer to things in the other file