replacing instance __setattr__
Robin Becker
robin at jessikat.fsnet.co.uk
Wed Jul 3 14:53:36 EDT 2002
Is there something intrinsically hard about overriding an instance's special methods? I'm using
python 2.2 and expected that it would be easy to wrap an existing __setattr__, but
it seems the class is searched first not the instance. Must I clone the class and
set the method on that?
#################
class A:
def __setattr__(self,n,v):
self.__dict__[n]=v
print 'hello world'
a=A()
print 'getattr(a,\'__setattr__\'):',getattr(a,'__setattr__',None)
a.b = 1
import new
a.__dict__['_saved__setattr__'] = a.__setattr__
def bingo(self,name,value):
print 'bingo wrapper',self, name, value
self._saved__setattr__(name,value)
a.__dict__['__setattr__']=new.instancemethod(bingo,a,a.__class__)
print 'getattr(a,\'__setattr__\'):',getattr(a,'__setattr__',None)
a.b=2 #I expected the instance method here ?????????
getattr(a,'__setattr__',None)('b',5)
###################
results in
C:\>\tmp\xxx.py
getattr(a,'__setattr__'): <bound method A.__setattr__ of <__main__.A instance at 0x007696A8>>
hello world
getattr(a,'__setattr__'): <bound method A.bingo of <__main__.A instance at 0x007696A8>>
hello world
bingo wrapper <__main__.A instance at 0x007696A8> b 5
hello world
--
Robin Becker
More information about the Python-list
mailing list