Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use Python <a href="http://docs.python.org/library/functions.html#property" rel="noreferrer">properties</a> to cleanly apply rules to each field separately, and enforce them even when client code tries to change the field:</p> <pre><code>class Spam(object): def __init__(self, description, value): self.description = description self.value = value @property def description(self): return self._description @description.setter def description(self, d): if not d: raise Exception("description cannot be empty") self._description = d @property def value(self): return self._value @value.setter def value(self, v): if not (v &gt; 0): raise Exception("value must be greater than zero") self._value = v </code></pre> <p>An exception will be thrown on any attempt to violate the rules, even in the <code>__init__</code> function, in which case object construction will fail.</p> <p><strong>UPDATE:</strong> Sometime between 2010 and now, I learned about <code>operator.attrgetter</code>:</p> <pre><code>import operator class Spam(object): def __init__(self, description, value): self.description = description self.value = value description = property(operator.attrgetter('_description')) @description.setter def description(self, d): if not d: raise Exception("description cannot be empty") self._description = d value = property(operator.attrgetter('_value')) @value.setter def value(self, v): if not (v &gt; 0): raise Exception("value must be greater than zero") self._value = v </code></pre>
 

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