python - python中的常量?

标签 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])

最佳答案

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

例如

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/

相关文章:

python - Happybase 与 hbase 连接时出错

python - 如何通过 Django 中的 'status' 变量对对象进行排序

python - 我遇到了来自 Django 的 404 错误消息。它说 "No location found matching the query"

python - PDB:如何检查嵌套堆栈帧中函数的局部变量?

python - cv2.fitEllipse 如何处理旋转的宽度/高度?

python - 每次调用 put 时 auto_now_add 属性是否都会更新?

python - 线程中的线程

python - 从两个列表中获取元素的所有组合?

python - 为什么所有双下划线变量都在类方法中被破坏

python - 了解 PyDict_Check 行为