<p>您好,我正在尝试使用从<a href="https://stackoverflow.com/questions/2682745/creating-constant-in-python">Creating constant in Python</a>(在链接的第一个答案中)找到的示例在python中创建一个const,并使用instance作为模块。在</p>
<p>第一个文件常数py有</p>
<pre><code># 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()
</code></pre>
<p>剩下的去测试.py例如。在</p>
^{pr2}$
<p>虽然我已经做了2个更改,因为我使用的是python3,但仍然有错误</p>
<pre><code>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
</code></pre>
<p>我不明白第5行的错误是什么。有人能解释吗?纠正这个例子也不错。提前谢谢。在</p>