Properties vs. get/set-methods

Duncan Booth duncan at
Fri Aug 23 10:44:28 CEST 2002

Michael 'Mickey' Lauer <mickey at> wrote in 
news:3d657c6f at

> 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.

> while trying to become familiar with the newstyle classes I'm now
> looking into the properties feature. I don't get the prefered usage
> for properties yet. They're not really an alternative to get/set-methods
> or are there? I mainly use get/set-methods when I want to save state
> and trigger an action, like e.g. in:
>   def setValue(self, val):
>     self.val = val
>     self.updateListeners( val )
Say you have lots of code which sets an attribute directly:

    anObj.val = 42

Now you suddenly decide that these updates should notify some listeners 
whenever it happens. You have a choice: either find everywhere you set the 
attribute and change it into a call to SetVal, or turn val into a property. 
Of course you then have to introduce another attributes to really save the 
value (__val might be a good name as it is the same as the original except 
that it is private).

> What am I missing here?

Not much. If you are willing to use an explicit function call to set an 
attribute this may be the easiest. If you want to hide the function call 
but still want side effects when setting the attribute then a property is 
good. Properties are also useful when you just want to introduce some 
debugging: instead of inserting trace statements everywhere a value is set, 
turn it into a property.

The get method on a property is good where you want to delay the evaluation 
of the property. e.g. If you have a complex structure bits of which are not 
loaded into memory until you access them. In this case the get method might 
hide the property by creating an instance variable of the same name when it 
is accessed.

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list