我在很多函数中声明了以下变量,因为我需要在每个函数中使用这些值。无论如何我可以在全局范围内声明它们或其他什么,比如我不必在我的所有方法中声明它们?我在我的一个类的实例方法上使用了所有这些方法。
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])
最佳答案
如果它们都在一个模块中,那么它们只存在于该模块的命名空间中,您不必担心名称冲突。 (而且您仍然可以将它们导入其他命名空间)
例如
MyModWithContstants.py
x = 0
y = 0
def someFunc():
dosomethingwithconstants(x,y)
我们也可以做到
另一个模组.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
关于python - python中的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1817144/