|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我想请问下动动手习题我如此写为何报错?
class Const:
def __init__(self):
self.cons = {}
def __setattr__(self, name, value):
if name in self.cons:
raise TypeError('常量无法改变!')
if not name.isupper():
raise TypeError('常量名必须由大写字母组成!')
self.cons[name] = value
import sys
sys.modules[__name__] = Const()
报错的内容为:
Traceback (most recent call last):
File "F:/Python练习/P050/constant.py", line 18, in <module>
sys.modules[__name__] = Const()
File "F:/Python练习/P050/constant.py", line 4, in __init__
self.cons = {}
File "F:/Python练习/P050/constant.py", line 7, in __setattr__
if name in self.cons:
AttributeError: 'Const' object has no attribute 'cons'
提前感谢!
本帖最后由 fall_bernana 于 2020-11-5 10:56 编辑
'''
你可以看你的错误。python的错误都是按运行的顺序报的。self.cons = {}后的一步是if name in self.cons:
所以说明当初始化的时候,self.cons ,对象调用cons 就会自动执行__setattr__方法,
然后__setattr__方法里面又是对象调用属性,而这个时候属性并没有建好。
为了避免这个问题需要用下面这种方式实现:
'''
- def __init__(self):
- object.__setattr__(self,'cons',{})
复制代码
|
|