如何在python中设置全局常量变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18224991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:14:53  来源:igfitidea点击:

how to set global const variables in python

pythonvariablesglobal-variablesconstdeclaration

提问by gen

I am building a solution with various classes and functions all of which need access to some global consants to be able to work appropriately. As there is no constin python, what would you consider best practice to set a kind of global consants.

我正在构建一个包含各种类和函数的解决方案,所有这些类和函数都需要访问一些全局常量才能正常工作。由于constpython中没有,您认为设置一种全局常量的最佳实践是什么。

global const g = 9.8 

So I am looking for a kind of the above

所以我正在寻找一种上述

edit: How about:

编辑:怎么样:

class Const():
    @staticmethod
    def gravity():
        return 9.8

print 'gravity: ', Const.gravity()

?

?

采纳答案by John La Rooy

You cannot define constants in Python. If you find some sort of hack to do it, you would just confuse everyone.

您不能在 Python 中定义常量。如果你找到某种黑客来做到这一点,你只会让每个人都感到困惑。

To do that sort of thing, usually you should just have a module - globals.pyfor example that you import everywhere that you need it

要做那种事情,通常你应该只有一个模块——globals.py例如,你可以在任何需要它的地方导入

回答by chhantyal

General convention is to define variables with capital and underscores and not change it. Like,

一般约定是用大写和下划线定义变量而不是改变它。喜欢,

GRAVITY = 9.8

However, it is possible to create constants in Python using namedtuple

但是,可以使用 Python 在 Python 中创建常量 namedtuple

import collections

Const = collections.namedtuple('Const', 'gravity pi')
const = Const(9.8, 3.14)

print(const.gravity) # => 9.8
# try to change, it gives error
const.gravity = 9.0 # => AttributeError: can't set attribute

For namedtuple, refer to docs here

对于namedtuple,请参阅此处的文档