mardi 12 juillet 2016

Error when __setattr__ for List

I am implementing all of the predefined function for a class, and I am stuck when i implement my__setattr__() for updating a list

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

Error:

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'

for normal variables other than list it does work fine, can anyone say what i am missing?

Aucun commentaire:

Enregistrer un commentaire