Main Content

Defining an object that is a modified standard type in Python

Archive - Originally posted on "The Horse's Mouth" - 2016-11-02 05:40:57 - Graham Ellis

If you want an object that behaves like a regular standard object but with the odd exception, you can define your own class which inherits from the system type. For example, we have redefined a dict as a specialDict in an example [here] where we've overridden just the __str__ method so that when we print out the object, we get the key/value pairs in a column, sorted by the value.

special class definition:

 class specialDict(dict):
         def __str__(this):
                 rzt = ""
                 sdk = sorted(list(this.keys()),key=lambda x: this[x])
                 for name in sdk:
                         rzt += "{1:} - {0:}\n".format(name,this[name])
                 return rzt


and the only difference in use (so easy to port to existing code) is the need to call a different constructor:

 counter = specialDict()

rather than

 counter = dict()

or

 counter = {}