Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First of all, it's almost always a bad idea to do such a thing. If only reason why you want that is making sure you don't make typos - there are better tools for that (think IDE or pylint). If you are a 100% positive that you need such a thing, here are two ways to do it:</p> <p>First way - you can do this with using <code>__setattr__</code> method. See <a href="http://docs.python.org/2/reference/datamodel.html#object.__setattr__" rel="nofollow">python <code>__setattr__</code> documentation</a></p> <pre><code>class Person(object): def __init__(self, first_name, last_name): self.__dict__['first_name'] = first_name self.__dict__['last_name'] = last_name def __setattr__(self, name, value): if name in self.__dict__: super(Person, self).__setattr__(name, value) else: raise AttributeError("%s has no attribute %s" %(self.__class__.__name__, name)) </code></pre> <p>and output:</p> <pre><code>In [49]: a = Person(1, 2) In [50]: a.a = 2 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in &lt;module&gt;() ----&gt; 1 a.a = 2 /usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in __setattr__(self, name, value) 8 super(Person, self).__setattr__(name, value) 9 else: ---&gt; 10 raise AttributeError("%s has no attribute %s" %(self.__class__.__name__, name)) AttributeError: Person has no attribute a </code></pre> <p>Alternatively, you can do this using <code>__slots__</code>(<a href="http://docs.python.org/2/reference/datamodel.html#slots" rel="nofollow">python <code>__slots__</code> documentation</a>):</p> <pre><code>class Person(object): __slots__ = ("first_name", "last_name") def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name </code></pre> <p>output:</p> <pre><code>In [32]: a = Person("a", "b") In [33]: a.first_name Out[33]: 'a' In [34]: a.a = 1 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in &lt;module&gt;() ----&gt; 1 a.a = 1 AttributeError: 'Person' object has no attribute 'a' </code></pre> <p>The first way is more flexible as it allows hacking this code even further through using <code>__dict__</code> directly, but that would be even more wrong than it is now. Second approach preallocates space for certain number of instance variables (references), which means less memory consumption.</p>
 

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