Python Forum
__getitem__ is readonly problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
__getitem__ is readonly problem
#1
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 ?
Reply
#2
collections.UserDict allows you to overwrite any "magic" method of dictionary - and add your own ones.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
Thanks soo much.
Reply
#4
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}
Reply
#5
(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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  __getitem__ Error stahorse 4 4,292 Jun-15-2022, 08:31 AM
Last Post: stahorse

Forum Jump:

User Panel Messages

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