[Tutor] When to use classes

boB Stepp robertvstepp at gmail.com
Sat Aug 19 11:52:45 EDT 2017


On Sat, Aug 19, 2017 at 3:07 AM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 19/08/17 08:52, Alan Gauld via Tutor wrote:
>
> Following up my own post - a sure sign of failure to communicate :-(
>
>> On 19/08/17 05:26, boB Stepp wrote:
>>
>>> related methods needs to share the same values and a class would tidy
>>> this up nicely without the need for any globals
>
>> Indeed, but its important to remember that class attributes
>> are in effect just global data confined to a smaller context,
>> and they share many of the same issues of global data.

This thought had occurred to me.  Sometimes I wish there was a
mechanism in Python to create a binding to data where both were
unchangeable/immutable.  Yes, I could use an immutable data type, but
if I bind an identifier to it that I want to *only* identify that
data, AFAIK it will always be possible for that identifier to be
rebound to a different object.

>> Classes don't remove the problems with globals, they just
>> limit the damage.
>
> I should have added that making the globals into instance
> variables rather than class attributes improves the
> situation still further since it effectively enables
> multiple "threads" of execution of your function sequence.
>
> The big issue I was alluding to is the solution whereby a
> sequence of functions sharing data is translated into
> a Class with class level variables and a bunch of
> static/class methods. (This is often seen in bad
> Java code). Shared instance data is much less likely
> to be changed in bad ways although still a form of global
> (within the instance).

I think the author was also emphasizing your points, but in a
different way.  He said:

<quote>
Maybe you decided to put your shared state into global variables
instead of creating a class. The single client of your module works
great. But what if you have a second client that needs its own copy of
the module state, or you need to use the module from multiple threads?
You are getting wacky results as the module trips over itself trying
to serve two masters. How can you have two copies of the global state?
Move it into a class! Each client has its own instance of the class
with its own state.
</quote>

> But creating classes just to avoid globalizing data
> should be a last resort solution. Classes should
> serve a conceptual function too in helping to understand
> the role of the functions within the overall system.
> And that, coincidentally, will usually result in the
> functions that share data being grouped in the
> same class.

I did say in my original post "...related methods...", but take the
importance of your point!



-- 
boB


More information about the Tutor mailing list