Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Immutability and Python

Thread Tools

Re: Immutability and Python

Ian Kelly
Posts: n/a
On Mon, Oct 29, 2012 at 10:12 AM, andrea crotti
<(E-Mail Removed)> 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

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Immutability and Python andrea crotti Python 8 11-08-2012 07:38 AM
Re: Immutability and Python Paul Rubin Python 7 10-29-2012 11:14 PM
Re: Immutability and Python Mark Lawrence Python 0 10-29-2012 03:55 PM
Re: Immutability and Python andrea crotti Python 0 10-29-2012 03:48 PM
Re: Immutability and Python andrea crotti Python 0 10-29-2012 03:44 PM