Dec-06-2016, 06:05 PM
Hi people!
I have been playing around with python a little and came across this:
consider the following code in Python3
Cheers
I have been playing around with python a little and came across this:
consider the following code in Python3
class THING: def __init__(self): self.number=10 self.valueDict={ 0: self.number } def __getitem__(self,index): return self.valueDict[index] def __setitem__(self,index,newVal): if index==0: self.number=newValdoes not work consistently:
Output:IN:a=THING()
IN:a[0]
Out: 10
IN:a[0]=9
IN:a[0]
Out: 10
The dictionary seems to address a different variable but it is not so:class THING: def __init__(self): # self.number=10 self.valueDict={ 0: self.number } def __getitem__(self,index): return self.valueDict[index] def __setitem__(self,index,newVal): if index==0: self.number=newValresults after initialisation are:
Error:AttributeError: 'THING' object has no attribute 'number'
my Workaround is:class THING: def __init__(self): self.number=10 self.valueDict={ 0: lambda: self.number } def __getitem__(self,index): return self.valueDict[index]() def __setitem__(self,index,newVal): if index==0: self.number=newVal
Output:IN:e=THING()
IN:e[0]
Out: 10
IN:e[0]=9
IN:e[0]
Out: 9
Now why is that, or better what is the purpose? ...and I know I could have just used a map for __setitem__ as wellCheers