Merging Objects
Michael Spencer
mahs at telcopartners.com
Mon Apr 3 16:04:27 EDT 2006
Cloudthunder wrote:
> Sorry, I don't understand, how does this solve my problem?
>
__getattr__ and __setattr__ allow you to set up dynamic delegation e.g.,
class Foo(object):
def __init__(self, **kw):
self.__dict__.update(kw)
def methFoo(self, x):
return "Foo.methFoo(%s,%s)" % (self,x)
class Bar(object):
def __init__(self, **kw):
self.__dict__.update(kw)
def methBar(self, x):
return "Foo.methFoo(%s,%s)" % (self,x)
class MultiDelegate(object):
def __init__(self, *args):
object.__setattr__(self,"_objects",args)
def __getattr__(self, attr):
for obj in self._objects:
if attr in dir(obj):
return getattr(obj, attr)
types = ",".join(obj.__class__.__name__ for obj in self._objects)
raise AttributeError, "%s object has no attribute '%s'" % (types, attr)
def __setattr__(self, attr, value):
# but you could do something more useful here too
raise TypeError, "Can't set attributes of MultiDelegate"
>>> f = Foo(a=1)
>>> b = Bar(b=2)
>>> m = MultiDelegate(f,b)
>>> m.a
1
>>> m.b
2
>>> m.methFoo(1)
'Foo.methFoo(<Untitled1.Foo object at 0x00A2A790>,1)'
>>> m.methBar(1)
'Foo.methFoo(<Untitled1.Bar object at 0x00A2A330>,1)'
>>>
HTH
Michael
More information about the Python-list
mailing list