Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中模拟常量变量_Python_Python 3.x_Constants - Fatal编程技术网

如何在python中模拟常量变量

如何在python中模拟常量变量,python,python-3.x,constants,Python,Python 3.x,Constants,您好,我正在尝试使用这个示例在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.ConstErro

您好,我正在尝试使用这个示例在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次更改,因为我使用的是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
回溯(最近一次呼叫最后一次):
文件“E:\Const\u in\u python\test.py”,第4行,在
常数魔法=23
文件“E:\Const_in_python\Const.py”,第5行,in_usetattr__
如果自我记录(姓名):
TypeError:“in”需要字符串作为左操作数,而不是dict
我不明白第5行的错误是什么。有人能解释一下吗?纠正这个例子也很好。提前感谢。

此行:

   if self.__dict__ in (name):
应该是

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

此行:

   if self.__dict__ in (name):
应该是

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

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

难道不是吗

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)
Python 3.2.3(默认,2012年5月3日15:51:42)
[GCC 4.6.3]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>导入常量
>>>常数魔法=23
>>>常数魔法=88
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“const.py”,第6行,在__
raise self.ConstError(“无法重新绑定常量(%s)”%name)
const.ConstError:无法重新绑定const(魔法)
你真的需要这个警察吗?很多Python代码在没有它的情况下似乎都能正常工作

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

难道不是吗

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)
Python 3.2.3(默认,2012年5月3日15:51:42)
[GCC 4.6.3]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>导入常量
>>>常数魔法=23
>>>常数魔法=88
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“const.py”,第6行,在__
raise self.ConstError(“无法重新绑定常量(%s)”%name)
const.ConstError:无法重新绑定const(魔法)
你真的需要这个警察吗?很多Python代码在没有它的情况下似乎都能正常工作

也许这就是您搜索的内容

支持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: 或

同样的答案:

也许就是你要搜索的

支持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: 或


同样的回答:

@gnibler谢谢,我真的不需要它,但知道它很好。我仍在尽可能地学习。:)@奇怪的事情。如果我尝试在pythonidle中重新绑定它,我会得到错误,但是在eclipse中,它只是使用新值重新绑定,没有任何错误。嗯,日食的虫子还是什么?@GeoPapas:你在尽力学习,这是件好事。了解Python的一个重要方面是,通常最好不要尝试附加其他语言的特性。你最终用一组(感知到的)问题换成另一组(实际的)问题。@gnibbler谢谢,我真的不需要它,但知道它很好。我仍在尽可能地学习。:)@奇怪的事情。如果我尝试在pythonidle中重新绑定它,我会得到错误,但是在eclipse中,它只是使用新值重新绑定,没有任何错误。嗯,日食的虫子还是什么?@GeoPapas:你在尽力学习,这是件好事。了解Python的一个重要方面是,通常最好不要尝试附加其他语言的特性。你最终用一组(感知到的)问题换取另一组(实际的)问题。