[Tutor] Property questions

Kent Johnson kent37 at tds.net
Sat Nov 13 22:49:13 CET 2004



John Fabiani wrote:
> Hi,
> 
> First how does python know which method to use as in:
> 
> size = property(getsize,setsize,delsize,'test doc')
> 
> I just have not seen anything/example that uses the dele of the "property".
> 
> so:
> 
> "size = something" # would call the getsize method because of the '=' sign?
No, this would call setsize because it is setting a new value for size

> "size" # would call the setsize because of what?
This calls getsize because it is getting the value
> 
> "dele size" # would call the delete method ??????? is that right?
del size
> 
> And how does one call the comment part??
> "size.__doc__" 

Note that all of these require an instance specifier, e.g. myObj.size.

Here is an example. Suppose you have a class Props defined like this:
class Props(object):
     def __init__(self):
         self._x = 0

     def _getx(self):
         print '_getx'
         return self._x

     def _setx(self, x):
         print '_setx'
         self._x = x

     def _delx(self):
         print '_delx'
         del self._x

     x = property(_getx, _setx, _delx, 'This is the "x" property')


Then you can use it like this:
 >>> p=Props()

Access x through _getx:
 >>> p.x
_getx
0

Set x through _setx:
 >>> p.x = 3
_setx
 >>> p.x
_getx
3

Access the doc string. You have to do this on the attribute of the 
*class*, not the instance
 >>> Props.x.__doc__
'This is the "x" property'

Delete the attribute:
 >>> del p.x
_delx

Now it's gone:
 >>> p.x
_getx
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "Property.py", line 7, in _getx
     return self._x
AttributeError: 'Props' object has no attribute '_x'

A good, though technical, guide to properties and descriptors is here: 
http://users.rcn.com/python/download/Descriptor.htm

Kent


More information about the Tutor mailing list