如何在python中模拟const变量

2024-09-28 13:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在尝试使用从Creating constant in Python(在链接的第一个答案中)找到的示例在python中创建一个const,并使用instance作为模块。在

第一个文件常数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()

剩下的去测试.py例如。在

^{pr2}$

虽然我已经做了2个更改,因为我使用的是python3,但仍然有错误

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行的错误是什么。有人能解释吗?纠正这个例子也不错。提前谢谢。在


Tags: nameinpyselfifvalue错误sys
3条回答

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

if self.__dict__ in (name):

不是吗

^{pr2}$

这修正了你的例子

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)

你真的需要这个警员黑客吗?很多Python代码似乎在某种程度上没有它也能工作

也许{a1}就是你要搜索的。在

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

例如:

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 github

同样的答案: Creating constant in Python

这条线:

   if self.__dict__ in (name):

应该是

^{pr2}$

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

相关问题 更多 >

    热门问题