[pyar] Como hacer un objeto inmutable
Mariano Guerra
luismarianoguerra en gmail.com
Vie Oct 28 09:09:22 ART 2011
2011/10/28 Facundo Batista <facundobatista en gmail.com>:
> 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
>>>>
>>> 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
:)
More information about the pyar
mailing list