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


Groups > comp.lang.python > #32418 > unrolled thread

Re: Immutability and Python

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2012-10-29 13:23 -0600
Last post2012-10-29 13:23 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#32418 — Re: Immutability and Python

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-10-29 13:23 -0600
SubjectRe: Immutability and Python
Message-ID<mailman.3043.1351538616.27098.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web