Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
bug or feature?
#1
Hi people!

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=newVal
does 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=newVal
results 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 well

Cheers
Reply


Messages In This Thread
bug or feature? - by Mettler - Dec-06-2016, 06:05 PM
RE: bug or feature? - by micseydel - Dec-06-2016, 06:24 PM
RE: bug or feature? - by Mettler - Dec-06-2016, 06:35 PM
RE: bug or feature? - by micseydel - Dec-06-2016, 06:38 PM
RE: bug or feature? - by nilamo - Dec-06-2016, 07:24 PM
RE: bug or feature? - by micseydel - Dec-06-2016, 07:28 PM
RE: bug or feature? - by Mettler - Dec-06-2016, 08:02 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020