Properties in Python

Peter Caven p.caven at ieee.org
Tue Jun 19 22:04:33 EDT 2001


I'm sure that many people reading this newsgroup are aware that the C#
(C-Sharp) language has a syntax for 'Properties' that allows a class
implementor to hide the implementation of  an instance's attribute behind a
'get'/'set' interface.
In Python terms this would look like:

class Demo:
      def __init__(self):
           self.attr1 = 1
           self.attr2 = 2

      def AMethod(self):
             pass

and where:

d = Demo()
a1 = d.attr1   # would actually execute something like:    d.attr1.get()
d.attr2 = 3    # would actually execute something like:     d.attr2.set(3)

So, instead of allowing direct access to the instance attributes, C#
actually executes 'get' and 'set' methods (if defined) for the attributes.
This lets a programmer change the behavior of the attributes defined in the
class (to have side-effects for example) without  changing any code written
by users of the class.

Does anyone have any ideas on how to do this (elegantly) in Python?
__getattr__ and __setattr__ don't seem to quite do it (ie.  inheritance).

Or, do the Python experts here think that this is not really such a good
idea?

-- Peter








More information about the Python-list mailing list