Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The easiest way to do this is using <code>__slots__</code>:</p> <pre><code>class A(object): __slots__ = [] </code></pre> <p>Instances of <code>A</code> are immutable now, since you can't set any attributes on them.</p> <p>If you want the class instances to contain data, you can combine this with deriving from <code>tuple</code>:</p> <pre><code>from operator import itemgetter class Point(tuple): __slots__ = [] def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) x = property(itemgetter(0)) y = property(itemgetter(1)) p = Point(2, 3) p.x # 2 p.y # 3 </code></pre> <p><strong>Edit</strong>: If you want to get rid of indexing either, you can override <code>__getitem__()</code>:</p> <pre><code>class Point(tuple): __slots__ = [] def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) @property def x(self): return tuple.__getitem__(self, 0) @property def y(self): return tuple.__getitem__(self, 1) def __getitem__(self, item): raise TypeError </code></pre> <p>Note that you can't use <code>operator.itemgetter</code> for the properties in thise case, since this would rely on <code>Point.__getitem__()</code> instead of <code>tuple.__getitem__()</code>. Fuerthermore this won't prevent the use of <code>tuple.__getitem__(p, 0)</code>, but I can hardly imagine how this should constitute a problem.</p> <p>I don't think the "right" way of creating an immutable object is writing a C extension. Python usually relies on library implementers and library users being <a href="http://mail.python.org/pipermail/tutor/2003-October/025932.html" rel="noreferrer">consenting adults</a>, and instead of really enforcing an interface, the interface should be clearly stated in the documentation. This is why I don't consider the possibility of circumventing an overridden <code>__setattr__()</code> by calling <code>object.__setattr__()</code> a problem. If someone does this, it's on her own risk.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload