property() usage - is this as good as it gets?

castironpi castironpi at
Fri Aug 22 18:44:42 CEST 2008

On Aug 22, 11:18 am, David Moss <drk... at> wrote:
> Hi,
> I want to manage and control access to several important attributes in
> a class and override the behaviour of some of them in various
> subclasses.
> Below is a stripped version of how I've implemented this in my current
> bit of work.
> It works well enough, but I can't help feeling there a cleaner more
> readable way of doing this (with less duplication, etc).
> Is this as good as it gets or can this be refined and improved
> especially if I was to add in a couple more attributes some fairly
> complex over-ride logic?
> #!/usr/bin/env python
> class A(object):
>     def __init__(self):
>         self._x = None
>         self._y = None
>     def _set_x(self, value):
>         self._x = value
>     def _get_x(self):
>         return self._x
>     x = property(_get_x, _set_x)
>     def _set_y(self, value):
>         self._y = value
>     def _get_y(self):
>         return self._y
>     y = property(_get_y, _set_y)

Within the bounds of Python, that's it.

In the cases where you're not executing code on 'get' or 'set', it
might be possible to have a default getter/setter, that just sets the
value of a variable name.  This keeps your interface the same across
inheritance and changes.  Possible to have it assign a default value

     def _set_z(self, value):
         self._z = value

     #def _get_z(self):
     #    return self._z

     z = property( True, _set_z ) #still gets self._z

Unless, you are looking at something 'periodic' or regular.  From
something I'm working on:

  def _getbalance( self ):
    return self._tree.geti(
      self.where+ self.lookup[ 'balance' ] )

  def _getparent( self ):
    return self._tree.getI(
      self.where+ self.lookup[ 'parent' ] )

Where 'balance' and 'parent' could both come from something generic:

balance= property( tree_lookup( 'balance' ) )
parent= property( tree_lookup( 'parent' ) )

They would have to take care to define 'self' properly and everything.

More information about the Python-list mailing list