mirror of
https://github.com/python/cpython.git
synced 2025-09-27 18:59:43 +00:00
Don't mention __slots__ as a technique for error avoidance
This commit is contained in:
parent
e960e22579
commit
28137a09d6
1 changed files with 6 additions and 10 deletions
|
@ -424,14 +424,9 @@ Finally, it's possible to constrain the list of attributes that can be
|
||||||
referenced on an object using the new \member{__slots__} class attribute.
|
referenced on an object using the new \member{__slots__} class attribute.
|
||||||
Python objects are usually very dynamic; at any time it's possible to
|
Python objects are usually very dynamic; at any time it's possible to
|
||||||
define a new attribute on an instance by just doing
|
define a new attribute on an instance by just doing
|
||||||
\code{obj.new_attr=1}. This is flexible and convenient, but this
|
\code{obj.new_attr=1}. A new-style class can define a class attribute named
|
||||||
flexibility can also lead to bugs, as when you meant to write
|
\member{__slots__} to limit the legal attributes
|
||||||
\code{obj.template = 'a'} but made a typo and wrote
|
to a particular set of names. An example will make this clear:
|
||||||
\code{obj.templtae} by accident.
|
|
||||||
|
|
||||||
A new-style class can define a class attribute named \member{__slots__}
|
|
||||||
to constrain the list of legal attribute names. An example will make
|
|
||||||
this clear:
|
|
||||||
|
|
||||||
\begin{verbatim}
|
\begin{verbatim}
|
||||||
>>> class C(object):
|
>>> class C(object):
|
||||||
|
@ -443,16 +438,17 @@ None
|
||||||
>>> obj.template = 'Test'
|
>>> obj.template = 'Test'
|
||||||
>>> print obj.template
|
>>> print obj.template
|
||||||
Test
|
Test
|
||||||
>>> obj.templtae = None
|
>>> obj.newattr = None
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
File "<stdin>", line 1, in ?
|
File "<stdin>", line 1, in ?
|
||||||
AttributeError: 'C' object has no attribute 'templtae'
|
AttributeError: 'C' object has no attribute 'newattr'
|
||||||
\end{verbatim}
|
\end{verbatim}
|
||||||
|
|
||||||
Note how you get an \exception{AttributeError} on the attempt to
|
Note how you get an \exception{AttributeError} on the attempt to
|
||||||
assign to an attribute not listed in \member{__slots__}.
|
assign to an attribute not listed in \member{__slots__}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
\subsection{Related Links}
|
\subsection{Related Links}
|
||||||
\label{sect-rellinks}
|
\label{sect-rellinks}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue