understanding operator overloading

Chris Rebert clp2 at rebertia.com
Fri Jun 1 15:29:29 EDT 2012


On Fri, Jun 1, 2012 at 9:39 AM, Josh Benner <sjbenner at gmail.com> wrote:
>
> Is there a good way to trace what's going on under the hood wrt operator
> overloading?
>
> I am trying to understand what is happening in the code and output listed
> below.
>
> Why doesn't __getitem__ in mylist return the same result as the builtin list
> object?

Because your class is old-style rather than new-style since it doesn't
subclass the `object` class. See
http://docs.python.org/reference/datamodel.html#newstyle . Thus,
you're getting the weird, more complicated, old-style semantics for
the operator in question.

<snip>
> ____code___________________________________________________
>
> class mylist():
<snip>

The fix is jus to subclass `object`:
class mylist(object):

Or use Python version 3.x, where all classes are new-style, and
old-style classes no longer exist.

Note that classes need only indirectly subclass `object` to be
new-style; so, if you have an actual class hierarchy, only the root of
your hierarchy needs to subclass `object` (this is also why
subclassing built-in types like `list` or `tuple` also results in
new-style classes: the built-in types themselves are `object`
subclasses).

Also, as a general point of coding style, one normally omits the
parentheses after the class name if one isn't subclassing anything.

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list