1

您好,我正在尝试使用在 Python 中创建常量(在链接的第一个答案中)中找到的这个示例在 python 中创建一个常量,并将实例用作模块。

第一个文件 const.py 有

# Put in const.py...:
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__ in (name):
            raise self.ConstError("Can't rebind const(%s)"%name)
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()

其余的例如到 test.py。

# that's all -- now any client-code can
import const
# and bind an attribute ONCE:
const.magic = 23
# but NOT re-bind it:
const.magic = 88      # raises const.ConstError
# you may also want to add the obvious __delattr__

尽管我做了 2 处更改,因为我使用的是 python 3,但我仍然遇到错误

Traceback (most recent call last):
  File "E:\Const_in_python\test.py", line 4, in <module>
    const.magic = 23
  File "E:\Const_in_python\const.py", line 5, in __setattr__
    if self.__dict__ in (name):
TypeError: 'in <string>' requires string as left operand, not dict

我不明白第 5 行错误是什么。谁能解释一下?纠正这个例子也很好。提前致谢。

4

3 回答 3

4

这看起来很奇怪(它是从哪里来的?)

if self.__dict__ in (name):

不应该

if name in self.__dict__:

这解决了你的例子

Python 3.2.3 (default, May  3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import const
>>> const.magic = 23
>>> const.magic = 88
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "const.py", line 6, in __setattr__
    raise self.ConstError("Can't rebind const(%s)"%name)
const.ConstError: Can't rebind const(magic)

你真的需要这个 const hack 吗?许多 Python 代码似乎在没有它的情况下也能正常工作

于 2012-10-03T10:04:57.203 回答
3

这一行:

   if self.__dict__ in (name):

应该

   if name in self.__dict__:

...您想知道属性是否在字典中,而不是字典是否在属性名称中(这不起作用,因为字符串包含字符串,而不是字典)。

于 2012-10-03T10:04:23.690 回答
0

也许kkconst - pypi是您搜索的内容。

支持 str、int、float、datetime const 字段实例将保持其基本类型行为。与 orm 模型定义一样,BaseConst 是管理 const 字段的常量助手。

例如:

from __future__ import print_function
from kkconst import (
    BaseConst,
    ConstFloatField,
)

class MathConst(BaseConst):
    PI = ConstFloatField(3.1415926, verbose_name=u"Pi")
    E = ConstFloatField(2.7182818284, verbose_name=u"mathematical constant")  # Euler's number"
    GOLDEN_RATIO = ConstFloatField(0.6180339887, verbose_name=u"Golden Ratio")

magic_num = MathConst.GOLDEN_RATIO
assert isinstance(magic_num, ConstFloatField)
assert isinstance(magic_num, float)

print(magic_num)  # 0.6180339887
print(magic_num.verbose_name)  # Golden Ratio
# MathConst.GOLDEN_RATIO = 1024  # raise Error, because  assignment allow only once

更多详细用法你可以阅读pypi url: pypi or github

相同的答案:在 Python 中创建常量

于 2015-12-26T11:10:51.047 回答