Add Properties to Instances?

Jeremy Bowers jerf at jerf.org
Sat Mar 12 13:41:56 EST 2005


On Sat, 12 Mar 2005 09:48:42 -0800, Martin Miller wrote:

> I'm trying to create some read-only instance specific properties, but the
> following attempt didn't work:

I'm going to echo Steven's comment: "What's the situation in which you
think you want different properties for different instances of the same
class?"

Another thought would be a custom __setattr__ and a bit of support:

Python 2.3.5 (#1, Mar  3 2005, 17:32:12) 
[GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sets
>>> class ReadOnlyAttributes(object):
...     def __init__(self):
...             self.__dict__['_readOnly'] = sets.Set()
...     def addReadOnly(self, key, value):
...             setattr(self, key, value)
...             self._readOnly.add(key)
...     def __setattr__(self, key, value):
...             if key in self._readOnly:
...                     raise AttributeError("can't set attribute")
...             self.__dict__[key] = value
... 
>>> r = ReadOnlyAttributes()
>>> r.a = 22
>>> r.a
22
>>> r.a = 23
>>> r.a
23
>>> r.addReadOnly("a", 22)
>>> r.a
22
>>> r.a = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 9, in __setattr__
AttributeError: can't set attribute
>>> r.addReadOnly("a", 23)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in addReadOnly
  File "<stdin>", line 9, in __setattr__
AttributeError: can't set attribute
>>>

I don't guarantee this completely fits the bill but I'm sure you can adapt
it from here. 

Also note that, strictly speaking, you can't make a "true" read-only
attribute, only one that alerts a programmer if they try the simple way.
In a pure-Python object, there is always a way in. This shouldn't worry
you if you're using Python ("We're all consenting adults here"), but you
should also be aware of that. That said, this is certainly useful in the
real world.



More information about the Python-list mailing list