I have a certain custom class that looks like a dictionary, and I want a method to be able to modify the values of the dictionary, but somehow I seem to be able to do so only by key-by-key modification (rather than self=...
assignment).
Obviously I want something more complex that the following MWE, but it demonstrates my issue (I would expect both class methods below to be equivalent):
class MyClass(dict):
def addone_notworking(self):
self = {key: (val+1) for key, val in self.items()}
# print({key: (val+1) for key, val in self.items()}) would return what I expect
def addone_working(self):
for k in self:
self[k] += 1 # self[k] = self[k] + 1 would work as well
a = MyClass({'a':1, 'b':2})
print(a, '<-- original')
a.addone_notworking()
print(a, "<-- should have added 1, but it hasn't")
a.addone_working()
print(a, '<-- works')
Results:
{'a': 1, 'b': 2} <-- original
{'a': 1, 'b': 2} <-- should have added 1, but hasn't
{'a': 2, 'b': 3} <-- works
What am I missing? I have found Python class methods changing self but I doubt it really applies ( bar = foo
statements would work even if bar
was a non-mutable type).
(Python 3.5, if it matters)