Properties vs. get/set-methods

Donnal Walter donnal at donnal.net
Fri Aug 23 10:33:45 EDT 2002


Michael 'Mickey' Lauer:
> Mark McEahern:
> >> When using properties, I can't use val to save the state.
> >> Accessing self.val would lead to infinite recursion here. So, if I
> >> want to save the state, I'd have to introduce another attribute.
> > 
> > The answer is embodied in this sample code:
> > 
> > class foo(object):
> > 
> >  def __init__(self):
> >    self._val = None
> > 
> >  def setVal(self, val):
> >    self._val = val
> > 
> >  def getVal(self):
> >    return self._val
> > 
> >  val = property(getVal, setVal)
> > 
> > Where's the infinite recursion in this?
> 
> Hmm... sure, I already stated that involving a second attribute
> is needed to save state. My original question about the real
> usage scenario for properties remains though.

Exactly. In the above sample what is gained by:

>>> x = foo()
>>> x.val = 'bar'
>>> x.val
'bar'

as opposed to:

>>> x.setVal('bar2')
>>> x.getVal()
'bar2'

Donnal Walter
Arkansas Children's Hospital



More information about the Python-list mailing list