* Mag Gam, on 24.06.2010 13:58:
I have been using python for about 1 year now and I really like the
language. Obviously there was a learning curve but I have a programing
background which made it an easy transition. I picked up some good
habits such as automatic code indenting :-), and making my programs
more modular by having functions.

I know that Python is very OOP friendly, but I could not figure out
why and when to use Classes in it. I mostly use it for simple text
parsing  I suppose when a program gets "complicated" I should start
using Classes. Are there any tips or tricks people use to "force" them
into the OOP mentality? I would like to force myself to learn the
Python way but so far I could not figure out WHY I would need a class
for this...

Use whatever paradigm that yields code that you easily understand. <g>

Having said that, the main use of a class is to model some data with an associated set of operations.

For this a class is merely a convenience, but sometimes the convenience can be so great that any other approach would be impractical in comparision.

In some cases a non-class approach ends up with a number of routines foo, bar, zlopf etc. that all take some argument of a "general" type and all internally has some "if it's really a BRACHYKLURB, do A, assuming that it has BRACHYKLURB-specific data, but if it's really a KNETCHOFICHUS, then do B, assuming that it has KNETCHOFICHUS-specific data, and as default, if it's none of those, do C".

This is a maintainance nightmare. You have to be sure that every such routine discriminates correctly on type, checking all possibilities and doing the right thing for each possibility. And you have to be sure of that in the face of possible additions of new subtypes, or removal of a subtype (maintainance).

Then the answer is to introduce some classes and OOP stuff.

In essence, instead of letting general routines awkwardly and error-prone choose the right type-specific routines depending on the object, let the object specify the right type-specific routines directly. :-)


Cheers & hth.,

- Alf

--
blog at <url: http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to