replacing instance __setattr__

Jeff Epler jepler at unpythonic.net
Fri Jul 5 14:27:33 EDT 2002


On Fri, Jul 05, 2002 at 04:45:45PM +0000, Alex Martelli wrote:
> 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

why not
    def changeSpecial(inst, name, function):
	method = new.instancemethod(function, inst, inst.__class__)
	setattr(inst, name, method)

>>> def f(self, x): print x
...
>>> class C: pass
...
>>> c = C()
>>> changeSpecial(c, 'f', f)
>>> c.f(3)
3

No setting of the __class__ attribute here, which is something that
gives me more willies than calling new.instancemethod and doing a
setattr on the instance...

Jeff





More information about the Python-list mailing list