My fight with classes :)

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Jun 12 11:47:05 CEST 2008

TheSaint a écrit :
> On 04:51, giovedì 12 giugno 2008 Terry Reedy wrote:
> First of all a big thank you, all.
>> def makeappender():
>>   data = ['','']
>>   def appender(val):
>>     <code that mutates data>
>>   return appender
> I'll give it a try. I just doubting if the data will be shared outside the
> function.

Each time makeappender is called, it returns a new appender function 
object with it's own 'data' object. So 'data' won't be shared between 
different instances of the appender function.

> Actually, my practice goes to send all variables to the functions and
> expecting a returned value.

Mostly a sane, sound and sensible approach IMHO - but doesn't work that 
well when the function needs to maintain own state between calls.

> Usually I'm not relying on that module's
> variables are read inside a function. Probably I got wrong learning or
> experiences.

As long as you only *read* module's globals from within a function, 
that's mostly ok. When you start *writing* them it may be time to 
reconsider the design (not that it's necessarily bad, but it's a 
possible signal that something is wrong).

>> For multiple functions, use classes.

Well... Closures are poor men's objects, or so they say (or is that the 
other way round ?-).

def make_person(name, age):
   state = dict(name=name, age=age)
   def set_name(new_name=None):
     state['name'] = new_name
   def get_name():
     return state['name']
   def grow():
     state['age'] += 1
   def get_age()
     return state['age']
   return set_name, get_name, grow, get_age

  toto_get_age) = make_person('toto', 42)

A bit cumbersome, indeed !-)

More information about the Python-list mailing list