Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32418

Re: Immutability and Python

References <CAF_E5Jbf0KJjDLV0jS-p_J9E4D8=_sPScgE+vkmkN2sMw=3aoA@mail.gmail.com> <1793477354.3492917.1351526431192.JavaMail.root@sequans.com> <CAF_E5JYRWxChJMHZc62d74Xnw88S2FhcXqot2V0hPuxfgbzbuw@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-10-29 13:23 -0600
Subject Re: Immutability and Python
Newsgroups comp.lang.python
Message-ID <mailman.3043.1351538616.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Oct 29, 2012 at 10:12 AM, andrea crotti
<andrea.crotti.0@gmail.com> wrote:
> Also because how doi I make an immutable object in pure Python?

I sometimes use namedtuples for this.

from collections import namedtuple

MyImmutableClass = namedtuple('MyImmutableClass', 'field1 field2 field3 field4')

If you want default arguments then use a factory function.  Or if you
want the class to have methods, then subclass it:

_MyImmutableClass = namedtuple('MyImmutableClass', 'field1 field2
field3 field4')

class MyImmutableClass(_MyImmutableClass):

    def __new__(cls, field1, field2, field3=None, field4=42):
        return super().__new__(cls, field1, field2, field3, field4)

    def get_sum(self):
        return self.field1 + self.field2

Cheers,
Ian

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Immutability and Python Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-29 13:23 -0600

csiph-web