python定义常量代码报错,请指教
# 该模块用于让 Python 支持常量操作, 模块名 constT.pyclass Const:
def __getattr__(self, name):
print('常量不存在')
def __getattribute__(self, name):
super().__getattribute__(name)
def __setattr__(self, name, value):
if name in self.__dict__:
raise TypeError('常量无法改变!')
if not name.isupper():
raise TypeError('常量名必须由大写字母组成!')
self.__dict__ = value
import sys
sys.modules = Const()
运行如下:不知道什么原因会报错,请指教
>>> import constT as co
>>> co.NAME = 1
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
co.NAME = 1
File "E:\python files\IDEL FILES\My py file\课后习题\constT.py", line 10, in __setattr__
if name in self.__dict__:
TypeError: argument of type 'NoneType' is not iterable def __getattribute__(self, name):
super().__getattribute__(name)
把这段去掉。
class Const:
def __getattr__(self, name):
print('常量不存在')
def __setattr__(self, name, value):
if name in self.__dict__:
raise TypeError('常量无法改变!')
if not name.isupper():
raise TypeError('常量名必须由大写字母组成!')
self.__dict__ = value
import sys
sys.modules = Const()
页:
[1]