Properties in Python
p.caven at ieee.org
Wed Jun 20 04:04:33 CEST 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
In Python terms this would look like:
self.attr1 = 1
self.attr2 = 2
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
More information about the Python-list