[pyar] Como hacer un objeto inmutable

Daniel Moisset dmoisset en machinalis.com
Vie Oct 28 09:46:37 ART 2011


2011/10/28 Mariano Guerra <luismarianoguerra en gmail.com>
>
> 2011/10/28 Facundo Batista <facundobatista en gmail.com>:
> >>>> class ReadOnlyPoint(object):
> > ...     _ro = False
> > ...     def __init__(self, x, y):
> > ...         self.x = x
> > ...         self.y = y
> > ...         self._ro = True
> > ...     def __setattr__(self, name, value):
> > ...         if self._ro:
> > ...             raise AttributeError("Read only instance")
> > ...         object.__setattr__(self, name, value)
>
> >>> p = ReadOnlyPoint(1,2)
> >>> p.__dict__
> {'y': 2, 'x': 1, '_ro': True}
> >>> p.__dict__['x'] = 2
> >>> p.x
> 2
> >>> p.__dict__['_ro'] = False
> >>> p.x = 10
> >>> p.x
> 10

Si es por dañino, la tuya (con clausuras) tambien se puede romper similarmente:

In [18]: p = ReadOnlyPoint(1,2)

In [19]: p.x
Out[19]: 1

In [20]: newx=10

In [21]: p.__class__ = ReadOnlyPoint(newx,p.y).__class__

In [22]: p.x
Out[22]: 10

:)

D.



More information about the pyar mailing list