gpt4 book ai didi

python - 为列表设置 __setattr__ 时出错

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:42 25 4
gpt4 key购买 nike

我正在实现一个类的所有预定义函数,当我实现我的__setattr__() 来更新列表时我卡住了

class testop:
def __init__(self):
self.li=[x*2 for x in list(range(5))]
def __getitem__(self,index):
return self.li[index]
def __setattr__(self,attr,value):
self.__dict__[attr]+=value #self.__dict__[attr].append(value)

if __name__=='__main__':
testop().li=3

错误:

line 10, in <module>
testop().li=30
File "C:/Users/Desktop/testop.py", line 3, in __init__
self.li=[x*2 for x in list(range(5))]
File "C:/Users/Desktop/testop.py", line 7, in __setattr__
self.__dict__[attr]+=value
KeyError: 'li'

对于 list 以外的普通变量,它确实工作正常,谁能说出我缺少的是什么?

Thanks for the answers and i am getting it clear why self.__dict__[attr] fail to find the key, Hmmmmmm but the normal variables it does work fine even when not adding it before hand to the dict?

最佳答案

问题是当 __init__ 被调用时,li 还不存在。

基本上,发生的事情是作为 __init__ 的一部分,您调用 __setattr__ 来设置 li。但是,li 还不存在,所以你得到一个键错误。

您需要做的是在尝试添加之前检查该属性是否存在。

class testop:
def __init__(self):
self.li = [x * 2 for x in list(range(5))]

def __getitem__(self, index):
return self.li[index]

def __setattr__(self, attr, value):
if attr in self.__dict__:
self.__dict__[attr] += value
else:
pass # Either create it or throw an exception, whatever you want to do.


if __name__ == '__main__':
testop().li = 3

关于python - 为列表设置 __setattr__ 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37887650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com