Re: Immutability and Python

Discussion in 'Python' started by Ian Kelly, Oct 29, 2012.

  1. Ian Kelly

    Ian Kelly Guest

    On Mon, Oct 29, 2012 at 10:12 AM, andrea crotti
    <> 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
    Ian Kelly, Oct 29, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. andrea crotti

    Immutability and Python

    andrea crotti, Oct 29, 2012, in forum: Python
    Replies:
    8
    Views:
    215
    Thomas Rachel
    Nov 8, 2012
  2. andrea crotti

    Re: Immutability and Python

    andrea crotti, Oct 29, 2012, in forum: Python
    Replies:
    0
    Views:
    167
    andrea crotti
    Oct 29, 2012
  3. andrea crotti

    Re: Immutability and Python

    andrea crotti, Oct 29, 2012, in forum: Python
    Replies:
    0
    Views:
    167
    andrea crotti
    Oct 29, 2012
  4. Mark Lawrence

    Re: Immutability and Python

    Mark Lawrence, Oct 29, 2012, in forum: Python
    Replies:
    0
    Views:
    176
    Mark Lawrence
    Oct 29, 2012
  5. Paul Rubin

    Re: Immutability and Python

    Paul Rubin, Oct 29, 2012, in forum: Python
    Replies:
    7
    Views:
    154
    Steven D'Aprano
    Oct 29, 2012
Loading...

Share This Page