[pyar] Como hacer un objeto inmutable

Facundo Batista facundobatista en gmail.com
Vie Oct 28 09:03:17 ART 2011


2011/10/28 Alejandro Santos <listas en alejolp.com>:

> Sin usar tuplas, namedtuples[1] ni extensiones en C, ¿cómo puedo hacer
> mi propio tipo de datos cuyas instancias sean inmutables garantizadas
> por el lenguaje? ¿es posible hacerlo usando clases, magia de
> decoradores y nada más?

>>> 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)
...
>>>
>>> rop = ReadOnlyPoint(2, 3)
>>> rop.x
2
>>> rop.x = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __setattr__
AttributeError: Read only instance
>>> rop.otra = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __setattr__
AttributeError: Read only instance
>>>

-- 
.    Facundo

Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/



More information about the pyar mailing list