Delegates
Delaney, Timothy
tdelaney at avaya.com
Fri Nov 17 00:56:04 EST 2000
Bah - left a bit of excess code in, and sent it under the wrong subject :(
This is better ;)
Just a snippet of something I put together today to allow delegates. This
may not be the best method, but it appears to work OK.
The parameters to the delegate.__init__ method can be anything which can
contain attributes. Normally these would be class instances, but they could
be modules, etc.
The list of delegates is checked against in the order they are defined. The
first matching attribute is returned.
It also handles the case that multiple classes in the heirarchy use
delegates. In this case it is important that the delegate.__init__ method is
the *first* __init__ method called, to maintain the behaviour that the
subclasses overrides take precedence over the base class.
class delegate:
""""""
def __init__(self, *delegates):
""""""
if self.__dict__.has_key('_delegate__delegates'):
self.__delegates.extend(list(delegates))
else:
self.__delegates = list(delegates)
def __getattr__(self, name):
""""""
if self.__dict__.has_key('_delegate__delegates'):
for d in self.__delegates:
try:
attr = getattr(d, name)
return attr
except AttributeError:
pass
raise AttributeError(name)
def addDelegate (self, delegate):
""""""
if self.__dict__.has_key('_delegate__delegates'):
self.__delegates.append(delegate)
else:
self.__delegates = [delegate]
if __name__ == '__main__':
class A:
""""""
i = 1
class B:
""""""
j = 2
class C:
""""""
k = 3
class D (delegate):
""""""
l = 4
def __init__(self):
""""""
delegate.__init__(self, B(), C())
class E (delegate, C, D):
""""""
m = 5
def __init__(self):
""""""
delegate.__init__(self, A(), C())
D.__init__(self)
e = E()
print e.m
print e.l
print e.k
print e.j
print e.i
print e.n
Tim Delaney
Avaya Australia
+61 2 9532 9079
More information about the Python-list
mailing list