oftenthe need to extend built-in data type is an indication that we're using the wrong sort of data type it is not always the casebut if we are looking to extend built-inwe should carefully consider whether or not different data structure would be more suitable for exampleconsider what it takes to create dictionary that remembers the order in which keys were inserted one way to do this is to keep an ordered list of keys that is stored in specially derived subclass of dict then we can override the methods keysvalues__iter__and items to return everything in order of coursewe'll also have to override __setitem__ and setdefault to keep our list up to date there are likely to be few other methods in the output of dir(dictthat need overriding to keep the list and dictionary consistent (clear and __delitem__ come to mindto track when items are removed)but we won' worry about them for this example so we'll be extending dict and adding list of ordered keys trivial enoughbut where do we create the actual listwe could include it in the __init__ methodwhich would work just finebut we have no guarantees that any subclass will call that initializer remember the __new__ method we discussed in objects in pythoni said it was generally only useful in very special cases this is one of those special cases we know __new__ will be called exactly onceand we can create list on the new instance that will always be available to our class with that in mindhere is our entire sorted dictionaryfrom collections import keysviewitemsviewvaluesview class dictsorted(dict)def __new__(*args**kwargs)new_dict dict __new__(*args**kwargsnew_dict ordered_keys [return new_dict def __setitem__(selfkeyvalue)'''self[keyvalue syntax''if key not in self ordered_keysself ordered_keys append(keysuper(__setitem__(keyvaluedef setdefault(selfkeyvalue)if key not in self ordered_keysself ordered_keys append(keyreturn super(setdefault(keyvaluedef keys(self)return keysview(selfdef values(self)