定义常量变量的最佳方法是什么python 3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50533812/
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 19:31:20  来源:igfitidea点击:

what is the best way to define constant variables python 3

pythonpython-3.xconstantsconfiguration-files

提问by TomE8

I am writing a program in python which contains many constant variables. I would like to create a file which will hold all these variables like .h file in C that contains many #define. I tried to use configparserhowever I didn't find it easy and fun to use.

我正在用 python 编写一个程序,其中包含许多常量变量。我想创建一个文件,该文件将包含所有这些变量,例如 C 中包含许多 #define 的 .h 文件。我尝试使用configparser,但是我觉得使用起来并不容易和有趣。

Do you know a better way?

你知道更好的方法吗?

回答by scharette

Python does not allow constant declarations like C or C++.

Python 不允许像 C 或 C++ 这样的常量声明。

Normally in Python, constants are capitalized (PEP 8standards) which helps the programmer know it's a constant.

通常在 Python 中,常量是大写的(PEP 8标准),这有助于程序员知道它是一个常量。

Ex. MY_CONSTANT = "Whatever"

前任。 MY_CONSTANT = "Whatever"

Another valid way of doing it which I don't use but heard of, is using a method:

另一种我不使用但听说过的有效方法是使用一种方法:

def MY_CONSTANT():
    return "Whatever"

Now in theory, calling MY_CONSTANT()acts just like a constant.

现在理论上,调用MY_CONSTANT()就像一个常数。

EDIT

编辑

Like the comments says, someone can go and change the value by calling

就像评论说的那样,有人可以通过调用来更改值

MY_CONSTANT = lambda: 'Something else'

but don't forget the same person can call MY_CONSTANT = "Something else"in the first example and change the initial value. In both cases it is unlikely but possible.

但不要忘记同一个人可以MY_CONSTANT = "Something else"在第一个示例中调用并更改初始值。在这两种情况下,这是不可能的,但可能的。

回答by 9000

There are no constants in Python, the way they exist in C or Java. You can imitate them by functions:

Python 中没有常量,它们以 C 或 Java 的方式存在。你可以通过函数来​​模仿它们:

def FOO():
  return "foo"

You can wrap the function call in a property, and thus make it look like a variable:

您可以将函数调用包装在一个属性中,从而使其看起来像一个变量:

class Const:
  @property
  def FOO(self):
    return "foo"

CONST = Const()  # You need an instance

if something == CONST.FOO:
  ...

With a bit of meta stuff, one can get unsettable attributes with a terse syntax:

通过一些元数据,可以使用简洁的语法获得不可设置的属性:

def const(cls):
    # Replace a class's attributes with properties,
    # and itself with an instance of its doppelganger.
    is_special = lambda name: (name.startswith("__") and name.endswith("__"))
    class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}
    def unbind(value):  # Get the value out of the lexical closure.
        return lambda self: value
    propertified_contents = {name: property(unbind(value))
                             for (name, value) in class_contents.items()}
    receptor = type(cls.__name__, (object,), propertified_contents)
    return receptor()  # Replace with an instance, so properties work.


@const
class Paths(object):
    home = "/home"
    null = "/dev/null"

Now you can access Paths.homeas a normal value, but can't assign to it. You can define several classes decorated with @const, as you might use several .hfiles.

现在您可以Paths.home作为普通值访问,但不能分配给它。您可以定义多个用 修饰的类@const,因为您可能会使用多个.h文件。

回答by Artem Nepo

You can use something like this:

你可以使用这样的东西:

Files structure:

文件结构:

myapp/
    __init__.py
    settings.py
    main.py

settings.py

设置.py

CONST_A = 'A'
CONST_B = 'B'

__init__.py

__init__.py

from . import settings as global_settings


class Settings:

    def __init__(self):
        for setting in dir(global_settings):
            if setting.isupper():
                setattr(self, setting, getattr(global_settings, setting))

    def __setattr__(self, attr, value):
        if not getattr(self, attr, None):
            super().__setattr__(attr, value)
        else:
            raise TypeError("'constant' does not support item assignment")


settings = Settings()

main.py

主文件

import settings

print(settings.CONST_A)  # prints A

settings.CONST_A = 'C'  # raises TypeError error

print(settings.CONST_A)  # prints A

settings.CONST_C = 'C'  # also able to add new constants
print(settings.CONST_C)  # prints C

Overwritten __setattr__ in Settingsclass makes all the attributes read-only. The only requirement is to have all the constants in your settings.pywritten in capital letters. But be aware, that it's not gonna work if you import variables directly:

Settings类中覆盖 __setattr__使所有属性都为只读。唯一的要求是将settings.py 中的所有常量都用大写字母书写。但请注意,如果您直接导入变量,它将无法正常工作:

from settings import CONST_A

print(settings.CONST_A)  # prints A

settings.CONST_A = 'C'  # sets C

print(settings.CONST_A)  # prints C

回答by Ankireddy

Python isn't preprocessed. You can just create a file constant.py

Python 没有经过预处理。你可以创建一个文件constant.py

#!/usr/bin/env python
# encoding: utf-8
"""
constant.py
"""

MY_CONSTANT = 50

Import constant.py file when ever you want constant values like below example.

当您需要常量值时导入 constant.py 文件,如下例所示。

#!/usr/bin/env python
# encoding: utf-8
"""
example.py
"""
import constant
print constant.MY_CONSTANT * 2

This way you can use constants across project.

这样您就可以跨项目使用常量。

You also have the option, if the constants are tied to a particular class and used privately within that class of making them specific to that class:

如果常量绑定到特定类并在该类中私下使用,您还可以选择使它们特定于该类:

class Foo(object):
   GOOD = 0
   BAD = 1

   def __init__(self...

If you want to define and use entire module, making them on top of the module

如果要定义和使用整个模块,请将它们放在模块之上

PIE = 3.47

class Foo(object):
   def __init__(self...

回答by saran3h

Just define a constants.py file and write all your constants. There is no other magic trick in Python. Use caps as a general convention.

只需定义一个 constants.py 文件并写入所有常量即可。Python 中没有其他魔术。使用大写作为一般约定。