Wandering Thoughts archives


How I use objects in Python

Python may be object oriented but it is also very flexible, so flexible that you can use its objects for all sorts of different things, many of them not very object-oriented by conventional definitions. I am not a traditional OO programmer, so I tend to use objects in Python in mostly non-traditional ways and for a number of different purposes.

(By 'objects' here I mean roughly 'classes and instances of classes'.)

This list is not complete, but it covers all of the uses of objects that come to mind (which probably means all of my major uses of them):

  • creating inheritance hierarchies for exceptions so I can have hierarchies of general and specific exceptions. I'm pretty sure that I'm usually overdesigning when I do this and that I rarely need an actual hierarchy as opposed to one or two separate exceptions.

  • as data records, ie the equivalent of C structs, in situations where just a list or a dictionary isn't enough. This 'bag of data' design pattern probably horrifies real OO people.

  • for polymorphism, when I have generic operations to apply to a variety of underlying object types. Usually I don't use much or any inheritance for this, because in Python you don't need to use inheritance to get polymorphism; you can just duck type.

    (This is a superset of objects as data records.)

  • for combining data and behavior together when it seems to make things simpler. My ideal is when all of the code that has to know about internal data storage details can be most conveniently put in one place (ie on the class), but I am willing to put methods on the side of a bag of data when it makes dealing with the data simpler.

    (Sometimes this involves polymorphism.)

Note that I am a heretic and don't believe in encapsulation for the sake of encapsulation. As I wrote recently, I consider OO to be a code structuring technique. Even when I have classic style data+behavior objects, some of the code related to them may not live in their class, and I'm perfectly happy to have 'bag of data' classes that also have some convenience methods attached to them.

(One of the reasons that I like Python is that it is so laid back about 'OO style'. Duck typing, public members, and other things mean that you aren't forced to structure your classes and code in certain ways merely to interact with other code, unlike in languages where, eg, polymorphism is only possible through inheritance.)

PS: yes, sometimes my freewheeling ways result in me more or less blowing my own foot off over time. If you want a demonstration of that, the sprawling mess of DWiki is on githib.

python/HowIUseObjects written at 00:19:09; Add Comment

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.