replacing instance __setattr__

Alex Martelli aleax at aleax.it
Fri Jul 5 12:45:45 EDT 2002


Robin Becker wrote:
        ...
>>Is there something intrinsically hard about overriding an instance's
>>special methods? I'm using
        ...
> well it seems Python not as dynamic as I believed. The object is
> searched last which seems completely counter-intuitive to me, but there
> you go.

Python is dynamic aplenty, but if it used special methods *found in
the instance* rather than those *found in the class*, as it did pre-2.2,
then metaclasses would be a mess (as they were pre-2.2).  Say that a
class object C defines a method __call__.  Now what happens when
we call C() ... ?  Should Python use C.__call__?  That's not what
we want -- we want C.__call__ used when INSTANCES of C are called,
NOT when C itself is called.  So, to avoid specialcasing and sundry
irregularities, it's best to generalize this.

This doesn't impede your abilities to customize an instance, without
affecting other instances of the same class:

def changeSpecial(inst, name, function):
    class Customized(inst.__class__): pass
    setattr(customized, name, function)
    inst.__class__ = Customized


Alex




More information about the Python-list mailing list