summaryrefslogtreecommitdiffstats
path: root/Doc/reference/datamodel.rst
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2007-09-05 13:36:44 (GMT)
committerGeorg Brandl <georg@python.org>2007-09-05 13:36:44 (GMT)
commit5768d577d396d25d8f00672616528d7a234025b6 (patch)
treea46c0ffedbf5f8f5d7d73c8895e9d48d41651130 /Doc/reference/datamodel.rst
parentd44a4e971918e9e8367f4469f43c6d429f11bdb2 (diff)
downloadcpython-5768d577d396d25d8f00672616528d7a234025b6.zip
cpython-5768d577d396d25d8f00672616528d7a234025b6.tar.gz
cpython-5768d577d396d25d8f00672616528d7a234025b6.tar.bz2
Backport from Py3k: Bug #1684991: explain lookup semantics for __special__ methods (new-style classes only).
Diffstat (limited to 'Doc/reference/datamodel.rst')
-rw-r--r--Doc/reference/datamodel.rst15
1 files changed, 15 insertions, 0 deletions
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
index 18ebe76..de649bb 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -1147,6 +1147,21 @@ and ``x`` is an instance of this class, then ``x[i]`` is equivalent [#]_ to
``x.__getitem__(i)``. Except where mentioned, attempts to execute an operation
raise an exception when no appropriate method is defined.
+For new-style classes, special methods are only guaranteed to work if defined in
+an object's class, not in the object's instance dictionary. That explains why
+this won't work::
+
+ >>> class C:
+ ... pass
+ ...
+ >>> c = C()
+ >>> c.__len__ = lambda: 5
+ >>> len(c)
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ TypeError: object of type 'C' has no len()
+
+
When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled. For example, some sequences may work well with retrieval