Operator overloading and __getattr__

Alex Martelli aleax at aleax.it
Thu Dec 25 11:50:49 EST 2003


John Roth wrote:

> "Samuel Kleiner" <sam at h41n2fls31o839.telia.com> wrote in message
> news:slrnbue5dp.72h.sam at h41n2fls31o839.telia.com...
>> I'm trying to create methods on method access- but __getattr__ fails
>> with operator overloading(below) Any suggestions? EG:
> 
> I haven't a clue what you're trying to do, but
> I believe it's not possible to install "magic methods"
> after the class is defined. Nor can you install
> them in the instance. They'll look like they've

It's true that (with newtype classes) special methods
can't be usefully "installed in the instance", but it's
not true that they can't usefully be "installed after
the class is defined" (as long as they ARE installed in
the _class_, not in the _instance_).

For example:

>>> class X(object): pass
...
>>> x = X()
>>> print x
<__main__.X object at 0x402dea8c>
>>> x.__str__ = lambda: "I am an X"
>>>
>>> print x
<__main__.X object at 0x402dea8c>
>>> X.__str__ = lambda self: "I am an X"
>>> print x
I am an X
>>>

Here we see that the first attempt, "installing in
the instance" in your terminology, was inoperative; but
the second one, "installing in the class" even though
well after the class was defined was perfectly operative
(on existing instances of the class, too -- of course it
also works just fine on any further new instance you may
create thereafter).

> been installed, but the interpreter will never
> execute them because it does not look there
> for them. It looks in special places in the C
> language structure for the class definition.

Yes, but the C code does go to the trouble of updating
those special places when you change the _class_ (NOT
when you change the instance).


If you want to add what amounts to a "per-instance
special method" you have, in practice, to make the
instance's class unique.  There are several ways to
do that, including on-the-fly and (better if you do
know all instances of a certain class will need such
treatment) in a __new__ method on the common baseclass.

I'm not sure what, exactly, the OP was trying to do
in his example code, but perhaps it can be accomplished
by the "give each instance a unique class" (and change
that class, when you want to "install special methods")
approach.


Alex





More information about the Python-list mailing list