Operator overloading and __getattr__

Shalabh Chaturvedi shalabh at cafepy.com
Tue Jan 13 01:39:13 EST 2004


Alex Martelli wrote:
> 
> 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).
> 

<snip>

> 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.

<snip>

Another option might be to use a descriptor on the class that looks up 
an instance attribute. A simplified example:

 >>> class X(object): pass
...
 >>> x = X()
 >>>
 >>> class iprop(object):
...     def __init__(self, ipropname):
...             self.ipropname = ipropname
...     def __get__(self, ob, cls):
...             if ob is not None and ob.__dict__.has_key(self.ipropname):
...                     return ob.__dict__[self.ipropname]
...
 >>> X.__str__ = iprop('__istr__')
 >>>
 >>> x.__istr__ = lambda: 'this is the instance x'
 >>>
 >>> print x
this is the instance x
 >>>

Any downside to this one?

--
Shalabh






More information about the Python-list mailing list