[Tutor] Immutable objects

Peter Otten __peter__ at web.de
Thu Aug 19 14:53:43 CEST 2010


Nitin Das wrote:

> class mymut(object):
> 
>   def __setattr__(self,k,v):
>       if hasattr(self,k):
>           if self.__dict__.get(k) == None:
>               self.__dict__[k] = v
>           else:
>               raise TypeError("Cant Modify Attribute Value")
>       else:
>           raise TypeError("Immutable Object")
> 
> 
> class mm(mymut):
>     x = ''
>     y = ''
>     def __init__(self,x,y):
>         self.x = x
>         self.y = y
> 
> 
> 
> p = mm(10,11)
> print p.x
> print p.y
> 
> 
> I have created this immutable object.Is there any other better
> implementation?

How about

>>> from collections import namedtuple
>>> Mm = namedtuple("Mm", "x y")
>>> p = Mm(10, 11)
>>> p.x
10
>>> p.y
11
>>> p.x = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>> p.z = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Mm' object has no attribute 'z'
>>>

Peter



More information about the Tutor mailing list