Python Forum

Full Version: __getitem__ is readonly problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my question here

how can i change readonly variable. this soo nonsense ):

my code
 
example = {"book": "Guliver", "game": "Age of Empires II"}

def __getitem__(self, key):
    if key == "game":
        print("Dont play game go to bed")
    elif key == "book":
        print("good choice")
        return dict.__getitem__(self,  key)

example.__getitem__ = __getitem__ # giving error. how can i fix ?
collections.UserDict allows you to overwrite any "magic" method of dictionary - and add your own ones.
Thanks soo much.
Or you can define a new class that acts like a dict, instead of modifying what the base dict is like:
>>> class mydict:
...   def __init__(self, items={}):
...     self._items = items
...   def __getitem__(self, key):
...     if key == "game":
...         raise Exception("*finger wags*, I can't let you do that, Dave")
...     return self._items.get(key)
...   def __setitem__(self, key, val):
...     self._items[key] = val
...   def __repr__(self):
...     return repr(self._items)
...
>>> x = mydict({"spam": "eggs", "game": True})
>>> x
{'spam': 'eggs', 'game': True}
>>> x["spam"]
'eggs'
>>> x["spam"] = "pancakes"
>>> x
{'spam': 'pancakes', 'game': True}
>>> x["game"]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 6, in __getitem__
Exception: *finger wags*, I can't let you do that, Dave
>>> x["game"] = False
>>> x
{'spam': 'pancakes', 'game': False}
(May-10-2017, 02:53 PM)nilamo Wrote: [ -> ]Or you can define a new class that acts like a dict, instead of modifying what the base dict is like:
The beauty of UserDict - you get all the methods that you don't need to override behaving as for a regular dictionary. Rewriting the whole dict interface may be a good exercise - but it will requite some effort, and thorough unit testing