473,498 Members | 1,671 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Potential improvement on delegation via explicit calls and super

Derived classes sometimes need to delegate portions of the work in overridden
methods to methods in their base classes. This was traditionally done with
explicit calls in python, e.g.,

class Derived(Left, Right):
def __init__(self, myarg, larg, rarg):
Left.__init__(self, larg)
Right.__init__(self, rarg)
self.data = myarg
print 'derived'

This worked great. It was possible to grab the appropriate arguments and send
them off to the right point. However, there was a problem.

class Base:
def __init__(self):
print 'base'

class Left(Base):
def __init__(self, arg):
Base.__init__(self)
print 'left'

class Right(Base):
def __init__(self, arg):
Base.__init__(self)
print 'right'

Now, when Derived(Left, Right) is initialized, Base.__init__ is called twice.
Sometimes that's O.K. Usually, it's a bad thing. Along came new-style
classes and 'super'. Unfortunately, super-based delegation doesn't play
nicely with traditional classes.
http://www.ai.mit.edu/people/jknight/super-harmful/
Moreover, it undermines any attempts to control which subset of arguments go
to which base class. This second problem is serious. In real life, base
classes differ from each other: I need to be able to send the right arguments
to each.

What I really want to do is explicitly delegate tasks to base classes,
choosing the arguments to send to each, but avoid double-calls resulting from
reconverging paths in the inheritance directed acyclic (pray it's acyclic)
graph.

I think the appended code may solve this problem, play nicely with traditional
classes, and allow the coder to send the right arguments to the right base
classes.

However, I'm new to python so I need some help.

1) Is my thinking reasonable or is there an better way to solve the
reconvergent path problem in python without undermining control over
arguments?

2) What's the proper way to rewrite the appended code. I'm sure it's
dreadfully inefficient. There are also probably ways to make its use more
intuitive, but I'm new to the language so I don't know the tricks yet.

Thanks for any tips,

-Robert Dick-

----
'''See the example at the bottom.'''

import inspect

def flatten_tree(tree):
'''Flatten a tree represented by nested lists'''
if isinstance(tree, list):
return [j for i in tree for j in flatten_tree(i)]
else:
return (tree,)

# Cache for delegation decisions.
call_cache = set()

def should_call(self, pos, supr):
'''Examines the inheritance DAG (might work for DCGs, too... haven't
checked) for 'self' to determine whether 'pos' is the leftmost derived
for 'supr'. Returns bool. Caches results for performance.'''
if (self.__class__, pos, supr) in call_cache: return True
ct = flatten_tree(inspect.getclasstree(inspect.getmro(s elf.__class__),
True))
# ct is a list of (class, (base classes)) tuples
# Find the first instance of the supr as a base class
do_call = pos is [cls for cls, bases in ct if supr in bases][0]
if do_call: call_cache.add((self.__class__, pos, supr))
return do_call

def delegate(self, pos, s_call, *pargs, **kargs):
'''If 'pos' is the leftmost derived for 's_call' in the 'self' inheritance
DAG, call s_call with 'pargs' and 'kargs'.'''
if inspect.ismethoddescriptor(s_call):
supr = s_call.__objclass__
else:
supr = s_call.im_class
if should_call(self, pos, supr):
s_call(self, *pargs, **kargs)

if __name__ == '__main__':
class Base(object):
def __init__(self):
delegate(self, Base, object.__init__)
print 'base'

class Left(Base):
def __init__(self):
delegate(self, Left, Base.__init__)
print 'left'

class Right(Base):
def __init__(self):
delegate(self, Right, Base.__init__)
print 'right'

class Der(Left, Right):
def __init__(self):
delegate(self, Der, Left.__init__)
delegate(self, Der, Right.__init__)
print 'der'

der = Der()
Jul 18 '05 #1
1 1342
Am Fri, 17 Dec 2004 02:17:38 -0600 schrieb Robert Dick:
Derived classes sometimes need to delegate portions of the work in overridden
methods to methods in their base classes. This was traditionally done with
explicit calls in python, e.g.,

class Base:
def __init__(self):
print 'base'

class Left(Base):
def __init__(self, arg):
Base.__init__(self)
print 'left'

class Right(Base):
def __init__(self, arg):
Base.__init__(self)
print 'right'


If you can change the source of Base, I would do it like
this:

class Base:
_init_done=0
def __init__(self):
if self._init_done:
return
self._init_done=1

# ... do init
Thomas

--
Thomas Güttler, http://www.thomas-guettler.de/
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2020
by: Gabriel Genellina | last post by:
Hi In the following code sample, I have: - a Worker class, which could have a lot of methods and attributes. In particular, it has a 'bar' attribute. This class can be modified as needed. - a...
7
3251
by: Rene Pijlman | last post by:
Section 6.5 "What is delegation?" of the FAQ says: "Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts...
0
1158
by: Eyal Lotem | last post by:
Python has a few issues many consider problems with regard to its variable namespacing. It seems that the local/global/builtins namespacing rules are ancient remnants of a different Python. ...
3
2400
by: Tony Johansson | last post by:
Hello! What does it mean with delegation and can you give me one example. //Tony
6
2823
by: Marc Castrechini | last post by:
This is a classic double hop delegation issue, however its the first time we are setting this up so we are doing something incorrectly. If we run through the IDE or using a localhost path on the...
5
1441
by: =?Utf-8?B?TWF5ZXI=?= | last post by:
Hi, I'm using two form classes and I would like all methods of the second class (the child class) to be managed by the first class (the main class). Is delegation the best solution for me? If so,...
6
3418
by: cbare | last post by:
Hello JS Gurus, One thing I haven't figured out about javascript is the treatment of __proto__. Inheritence, whether prototypes or class-based, is just a shorthand form of delegation (leaving...
12
7169
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? ...
13
1441
by: barcaroller | last post by:
What is the common way/design-pattern (if any) in C++ for delegating function calls that are not handled by a certain class. Public inheritance would be one way but not all classes are meant to...
0
7005
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7168
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6891
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
4595
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3096
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3087
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1424
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
659
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
293
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.