__getitem__ is readonly problem - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: __getitem__ is readonly problem (/thread-3264.html) |
__getitem__ is readonly problem - harun2525 - May-10-2017 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 ? RE: __getitem__ is readonly problem - volcano63 - May-10-2017 collections.UserDict allows you to overwrite any "magic" method of dictionary - and add your own ones.
RE: __getitem__ is readonly problem - harun2525 - May-10-2017 Thanks soo much. RE: __getitem__ is readonly problem - nilamo - May-10-2017 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} RE: __getitem__ is readonly problem - volcano63 - May-10-2017 (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
|