Issue with new-style classes and operators
Jan Decaluwe
jan at jandecaluwe.com
Wed Nov 27 05:17:27 EST 2002
Alex Martelli wrote:
>
> 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.
But what makes operator methods so special that they should be treated
so differently from ordinary methods?
As far as I am concerned, operator syntax is just convenience, not
concept. The line between operators and ordinary methods is thin
and arbitrary.
For example, take 's.extend(x)', with s a list. The documentation states
that it is the same as 's[len(s):len(s)] = x'. Another way to
do it is 's += x'.
Yet, if you try it with my example class, the 'extend' would work fine,
and while the 2 operator-style statements would give a type error.
What's logical about that?
My conclusion would be that if __getattr__ doesn't look up "special"
methods, it should'nt look up "ordinary" methods either, but rely
on inheritance for those also.
Regards, Jan
--
Jan Decaluwe
mailto:jan at jandecaluwe.com
More information about the Python-list
mailing list