property and virtuality

Greg Ewing greg at cosc.canterbury.ac.nz
Sun Apr 3 22:37:49 EDT 2005


Laszlo Zsolt Nagy wrote:
> 
> My problem is about properties and the virtuality of the methods. I 
> would like to create a property whose get and set methods
> are virtual.

You might find the following function useful, which I
developed for use in PyGUI.

   def overridable_property(name, doc = None):
     """Creates a property which calls methods get_xxx and set_xxx of
     the underlying object to get and set the property value, so that
     the property's behaviour may be easily overridden by subclasses."""

     getter_name = intern('get_' + name)
     setter_name = intern('set_' + name)
     return property(
         lambda self: getattr(self, getter_name)(),
         lambda self, value: getattr(self, setter_name)(value),
         None,
         doc)

Usage example:

   class MyClass(object):
     ...
     spam = overridable_property('spam', "Favourite processed meat product")
     ...

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list