[Tutor] Immutable objects

Nitin Das nitin.162 at gmail.com
Thu Aug 19 16:47:57 CEST 2010


Thanks guys,
    NamedTuple implementation is preety nice solution.

--nitin

On Thu, Aug 19, 2010 at 6:28 PM, Peter Otten <__peter__ at web.de> wrote:

> Peter Otten wrote:
>
> > 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'
> >>>>
>
> By the way, you can see the class definition with
>
> namedtuple("Mm", "x y", verbose=True)
>
> Peter
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100819/f32670e9/attachment.html>


More information about the Tutor mailing list