Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #32418 > unrolled thread
| Started by | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| First post | 2012-10-29 13:23 -0600 |
| Last post | 2012-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.
Re: Immutability and Python Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-29 13:23 -0600
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2012-10-29 13:23 -0600 |
| Subject | Re: 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
Back to top | Article view | comp.lang.python
csiph-web