Making immutable instances
Alex Martelli
aleax at mail.comcast.net
Wed Nov 23 23:44:08 EST 2005
Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
...
> > Remember that your redefined __setattr__ IS "in place" even when
> > you're initializing your istance, so remember to delegate attribute
> > setting to the superclass (the other special methods mentioned above
> > are less likely to byte you).
>
> So, for a class that needs to set attributes in __init__ (but after
> that, become immutable), how do I get around this? Should I make a
As I said, you delegate attribute setting to the superclass. E.g:
>>> class Immut(object):
... def __setattr__(*a): raise TypeError, 'immutable'
... def __init__(self, v=23):
... super(Immut,self).__setattr__('v', v)
...
>>> x=Immut()
>>> x.v
23
>>> x.v=42
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in __setattr__
TypeError: immutable
>>>
Alex
More information about the Python-list
mailing list