Multiple inheritance: Interface problem workaround, please comment this

Steven Bethard steven.bethard at gmail.com
Thu Apr 7 12:23:09 EDT 2005


Axel Straschil wrote:
> I solved all my problems for pythons multiple inheritance with this ng,
> thaks to all again, but there is one think I still dislike:
> 
> class A(object):
> 	def __init__(self, a=None, **__eat): 
> 		print "A"
> 		super(A, self).__init__()
> class B(object):
> 
> 	def __init__(self, b=None, **__eat): 
> 		print "B"
> 		super(B, self).__init__()
> 
> class AB(A, B):
> 	def __init__(self, a=None, b=None): 
> 		super(AB, self).__init__(a=a, b=b)
> 
> ab = AB()
> 
[snip]
>  
> My problem: If you make a coding mistake, and the mistake does not give
> a runtime error becouse **__eat is a hungry evil beast, it would be very
> hard to debug ... think of a wrong written parameter!

I also agree that this style is not pretty.  What are A and B in your 
real code?  I would suggest that rather than this architecture, you 
might do better to either:
    (1) make A or B a mixin class that doesn't need __init__ called, or
    (2) make class AB inherit from A and delegate to B (or vice versa)
For example:

py> class A(object):
...     def __init__(self, x):
...         self.x = x
...
py> class B(object):
...     def __init__(self, y):
...         self.y = y
...
py> class C(object):
...     def m(self):
...         return self.x, self.y
...
py> class ABC(A, C):
...     def __init__(self, x, y):
...         super(ABC, self).__init__(x)
...         self._b = B(y)
...     def __getattr__(self, name):
...         return getattr(self._b, name)
...
py> a = ABC(1, 2)
py> a.x
1
py> a.y
2
py> a.m()
(1, 2)

Note that A is the "true" superclass, B is delegated to, and C is just a 
mixin class.

STeVe



More information about the Python-list mailing list