【问题标题】:how to simulate const variable in python如何在python中模拟const变量
【发布时间】:2012-10-03 10:00:57
【问题描述】:

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

第一个文件 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 行错误是什么。谁能解释一下?纠正这个例子也很好。提前致谢。

【问题讨论】:

    标签: python python-3.x constants


    【解决方案1】:

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

    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 代码似乎都可以工作

    【讨论】:

    • @gnibbler 谢谢,我真的不需要它,但很高兴知道。我仍在尽我所能学习。 :)
    • @gnibbler 奇怪的事情。如果我尝试在 python IDLE 中重新绑定它,我会收到错误消息,但在 Eclipse 中,它只是用新值重新绑定而没有任何错误。嗯 eclipse 的错误之类的?
    • @GeoPapas:你正在努力学习任何你能学到的东西,这是一件好事。了解 Python 的重要一点是,通常最好不要尝试使用其他语言的功能。你最终会用一组(感知的)问题来换取另一组(实际的)问题。
    【解决方案2】:

    这一行:

       if self.__dict__ in (name):
    

    应该是

       if name in self.__dict__:
    

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

    【讨论】:

      【解决方案3】:

      也许 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 github

      同样的答案: Creating constant in Python

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-17
        • 2022-08-11
        • 2020-07-28
        • 1970-01-01
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多