python中的常量?

dev*_*ium 3 python

我在很多函数中声明了以下变量,因为我需要在每个函数中使用这些值.无论如何我可以在全球范围内声明它们,例如我不必在我的所有方法中声明它们吗?我在我的一类实例方法中使用所有这些方法.

x = 0
y = 1
t = 2
Run Code Online (Sandbox Code Playgroud)

在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])
Run Code Online (Sandbox Code Playgroud)

And*_*ffe 12

如果它们都在一个模块中,那么它们只存在于该模块的命名空间中,您不必担心名称冲突.(你仍然可以将它们导入其他的名称空间)

例如

MyModWithContstants.py

x = 0
y = 0

def someFunc():
  dosomethingwithconstants(x,y)
Run Code Online (Sandbox Code Playgroud)

我们也可以这样做

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
Run Code Online (Sandbox Code Playgroud)


Rya*_*rom 5

除了单独的模块技巧,如果我想要它们在同一个模块中,我会经常将它们放在一个类中,如下所示:

class PathConstants(object):
    CSIDL_DESKTOP = 0
    CSIDL_PROGRAMS = 2

def get_desktop():
    return _get_path_buf(PathConstants.CSIDL_DESKTOP)
Run Code Online (Sandbox Code Playgroud)

如果你想让它们更加稳定,那么你可以进行setattr throw:

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"
Run Code Online (Sandbox Code Playgroud)

追溯:

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
Run Code Online (Sandbox Code Playgroud)