python - Use __get__, __set__ with dictionary item? -


is there way make dictionary of functions use set , statements , use them set , functions?

class thing(object):     def __init__(self, thingy)         self.thingy = thingy     def __get__(self,instance,owner):         return thingy     def __set__(self,instance,value):         thingy += value  thedict = {"bob":thing(5), "suzy":thing(2)}  thedict["bob"] = 10 

wanted result 10 goes set function , adds existing 5

print thedict["bob"] >>> 15 

actual result dictionary replaces entry numeric value

print thedict["bob"] >>> 10 

why can't make function like.. thedict["bob"].add(10) because it's building off existing , working function uses set , get. case i'm working edge case , wouldn't make sense reprogram make work 1 case.

i need means store instances of set/get thingy accessible doesn't create layer of depth might break existing references.

please don't ask actual code. it'd take pages of code encapsulate problem.

you if can (also) use specialized version of dictionary aware of thing class , handles separately:

class thing(object):     def __init__(self, thingy):         self._thingy = thingy     def _get_thingy(self):         return self._thingy     def _set_thingy(self, value):         self._thingy += value      thingy = property(_get_thingy, _set_thingy, none, "i'm 'thingy' property.")  class thingdict(dict):     def __getitem__(self, key):         if key in self , isinstance(dict.__getitem__(self, key), thing):             return dict.__getitem__(self, key).thingy         else:             return dict.__getitem__(self, key)      def __setitem__(self, key, value):         if key in self , isinstance(dict.__getitem__(self, key), thing):             dict.__getitem__(self, key).thingy = value         else:             dict.__setitem__(self, key, value)   thedict = thingdict({"bob": thing(5), "suzy": thing(2), "don": 42})  print(thedict["bob"])  # --> 5 thedict["bob"] = 10 print(thedict["bob"])  # --> 15  # non-thing value print(thedict["don"])  # --> 42 thedict["don"] = 10 print(thedict["don"])  # --> 10 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -