index ( value ) del self def pop ( self, index =- 1 ): value = self del self return valueĮvery time we customize a bit of core functionality on a list or dict subclass, we’ll need to make sure we customize other methods that also include exactly the same functionality (but which don’t delegate to the method we overrode). This class is a bit nonsensical (no it’s not a Python Morsels exercise fortunately), but we’re focused less on the class itself and more on the issue with inheriting from list:ĭef remove ( self, value ): index = self. The _iter_ and _eq_ methods will skip over this hole when comparing two HoleList classes as “equal”. This list will customize _delitem_ to not actually delete an item but to instead leave a “hole” where that item used to be. We’ll make a custom list that inherits from the list constructor and overrides the behavior of _delitem_, _iter_, and _eq_. The list and set classes have similar problems to the dict class. Likewise, get and pop don’t call _getitem_, as you might expect they would. When inheriting from dict to create a custom dictionary, we’d expect update and _init_ would call _setitem_ and pop and setdefault would call _delitem_. def pop ( self, key, default = DEFAULT ): if key in self or default is DEFAULT : value = self del self return value else : return default def setdefault ( self, key, value ): if key not in self : self = value We could try to implement this by customizing deletion and setting of key-value pairs.ĭEFAULT = object () class TwoWayDict ( dict ): #. There will always be an even number of elements in this dictionary.Īnd if d = v is True then d = k will always be True also. When a key-value pair is added, the key maps to the value but the value also maps to the key. We’d like to make a dictionary that’s bi-directional. My examples will focus on dict and list since those are likely more commonly sub-classed. I’m writing this article to explain why I often don’t recommend inheriting from these built-in classes in Python. While creating and solving many exercises involving custom collections, I’ve realized that inheriting from list, dict, and set is often subtly painful.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |