Operator overloading and __getattr__
Bengt Richter
bokr at oz.net
Tue Dec 23 07:12:56 EST 2003
On Mon, 22 Dec 2003 10:03:03 -0600, Samuel Kleiner <sam at h41n2fls31o839.telia.com> wrote:
>I'm trying to create methods on method access- but __getattr__ fails
>with operator overloading(below) Any suggestions? EG:
First please explain why you are trying to do whatever it is you're trying to do ;-)
What do you mean "create methods"? A method like __add__ is returned by
the attribute mechanism as a bound method, with self bound to something, and
other being bound during the call of the method to the other operand. You
are apparently trying to intercept this for _instance_ attribute access, when
there exists no same_named method in class NewM or dict (since lookup of methods
will bypass __getattr__ for new style classes). (Maybe you want to override __getattribute__,
which is trickier, but I still don't know how you are going to supply a compatible pair
of operands for __add__ unless you hope to do something useful by ignoring self. But
a method grabbed from some random operand is not going to do that, in general). So what
are you trying to do? I seem to be missing it.
What do you expect to be self and other in this scenario?
BTW, IWT type(name) would be str all the time, so I don't know what the code
is doing, or even trying to do ;-/
>
>class NewM(dict):
> def __getattr__(self,name):
> def fi(m):
> if type(name) in self:
> self[type(name)]=self[type(name)].__dict__[name](m)
> else:
> self[type(name)]=m
> return fi
>
>p=int(2)
>s=NewM()
>print p.__add__(2)
>print s.__add__(2)
>print p+2
>print s+2
>
>Causes TypeError on the last line
I doubt if that's the first problem ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list