Skip to main content
 首页 » 编程设计

python之如何在python中模拟const变量

2025年05月04日14telwanggs

你好,我正在尝试使用从 Creating constant in 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 行的错误是什么。谁能解释一下?纠正这个例子也很好。提前致谢。

请您参考如下方法:

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

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 代码似乎没有它也能正常工作