Issue with new-style classes and operators

Alex Martelli aleax at aleax.it
Mon Nov 25 08:28:33 EST 2002


Jan Decaluwe wrote:

> Hi:
> 
> I'm confused by the following behavior of new-style classes
> and operators:
> 
>     class MyInt(object):
>         def __init__(self, val):
>             self.val = val
>         def __getattr__(self, attr):
>             return getattr(self.val, attr)
> 
> 
>> python
> Python 2.2.2 (#1, Oct 16 2002, 19:59:11)
> [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> from MyInt import MyInt
>>>> a = MyInt(3)
>>>> a.__add__(4)
> 7
>>>> a + 4
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: unsupported operand types for +: 'MyInt' and 'int'
> 
> 
> 
> I don't think is can be the intention. Or can it?

Yes it can.  The idea is that operators should rely on special
methods defined by the TYPE (class) of the object they're working
on, NOT on special methods defined just by the OBJECT itself and
not by its class.  Doing otherwise (as old-style classes did, and
still do for compatibility) is untenable in the general case, for
example whenever you consider a class and its metaclass (given that
the metaclass IS the class object's type, no more and no less).

So, for example,  a + b  now looks for a potential __add__ special
method, NOT in a itself, but rather in type(a)  [except, for
compatibility, when a instances an old-style class].  I had some
difficulty understanding that, early on in the lifecycle of Python
2.2, but when the notion "clicked" I saw it made a lot of sense.

So, to wrap an arbitrary object X in such a way that X's special
methods will be used by any operator, you need to ensure you do
the wrapping with a _class_ that exposes said special methods.
That's generally easiest to do with a factory function with a
nested class that uses inheritance, but you have many other choices
depending on what exactly you're trying to accomplish.


Alex




More information about the Python-list mailing list