From 5768d577d396d25d8f00672616528d7a234025b6 Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Wed, 5 Sep 2007 13:36:44 +0000 Subject: [PATCH] Backport from Py3k: Bug #1684991: explain lookup semantics for __special__ methods (new-style classes only). --- Doc/reference/datamodel.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 18ebe76df93..de649bbd4ef 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 "", line 1, in + 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