[Tutor] When to use classes

Cameron Simpson cs at cskk.id.au
Sat Aug 19 18:39:49 EDT 2017


On 19Aug2017 11:00, boB Stepp <robertvstepp at gmail.com> wrote:
>On Sat, Aug 19, 2017 at 4:04 AM, Peter Otten <__peter__ at web.de> wrote:
[...]
>> The lesson is that Python already provides some powerful ready-to-use
>> classes that take you a long way without having to write your own custom
>> classes.
>
>In my beginning experiments to date writing classes, I have often
>while writing my toy examples realized, "Why am I writing a class?
>Python already does this more straightforwardly with <insert Python
>featured code here>."  Of course not knowing all of Python I sometimes
>don't realize this until well after I wrote the unneeded class.

Personally, I do this a lot. It does cost some time, but it also has 
advantages. You get to explore the problem space from the point of view of your 
own needs, and you get insight into the costs/benefits of various ways of doing 
things.

Then you can come back to the presupplied library do various things: understand 
why its interfaces may be designed the way they were, refactor your code (the 
larger problem) on top of the presupplied library, and sometimes decide that 
the presupplied library doesn't meet your needs (or meets them poorly), and 
then you have this useful additional library of your own.

The flipside is to do a little research and start with the presupplied library 
and take that as far as it will go, then build on that. Particularly when the 
library solves some problem you find boring. Also, the presupplied library 
often covers corner cases you may miss - it has (probablym hopefully) been well 
debugged - writing your own has that cost.

You get less insight into internals, but you also get off the ground faster.

>> Another alternative to (explicit) classes are generators which are an
>> elegant way to hold state and provide a simple interface.
[...]
>I hope I don't forget this point between now and when I get the
>database part of my project going!

One thing that I think can be important is to code the upper layers in the 
terms of your larger problem, not in terms of the lower level library's 
interface. In between the two will be functions or methods of your own whose 
interfaces are your own operation, and which call the library to accomplish the 
task, providing some separation between a natural expression of your upper 
level problem and what you might write if you were building from the bottom and 
thinking in the library's terms.

Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)

Ride to not crash. Dress to crash. Live to ride to not crash again.
- Lawrence Smith, DoD#i, lawrence at msc.cornell.edu


More information about the Tutor mailing list