[Tutor] quirky multiple inheritance example!?

Kent Johnson kent37 at tds.net
Thu Feb 9 00:50:49 CET 2006


Marcus Goldfish wrote:
> Hi,
>  
> I ran across a strange problem using mulitple inheritance that I hope 
> someone can explain.  Basically, I am implementing a Publisher pattern, 
> and when I try to add threading, the order I list Base classes matters!  
> Here is the short sample code-- all help explaining this is appreciated!
>  
> Thanks,
> Marcus
>  
> ---
> import threading
>  
> class Publisher(object):
>    def __init__(self): self.listeners = {} 
>    def register(self, id, object):
>       self.listeners[id] = self.listeners.get(id, object)
>  
>  
> # This *FAILS* with AttributeError: 'FancyPublisher'
> # object has no attribute 'listeners'
> class FancyPublisher(threading.Thread, Publisher):
>    def __init__(self):
>       super(FancyPublisher, self).__init__()
>  
> F = FancyPublisher()
> F.register('me', None)   
>  
>  
> # However, this succeeds!?
> class FancyPublisher(Publisher, threading.Thread):
>    def __init__(self):
>       super(FancyPublisher, self).__init__()
>  
> F = FancyPublisher()
> F.register('me', None)   

Wow, the third (sort of) threading question in a week!

The problem is that neither Publisher nor threading.Thread calls 
super(...).__init__() in *its* __init__() method, so you are only 
initializing one of your base classes. I don't think your second 
FancyPublisher would work when you actually tried to run it as a thread.

One solution is to just call both base class __init__() methods directly:
class FancyPublisher(Publisher, threading.Thread):
    def __init__(self):
       FancyPublisher.__init__(self)
       threading.Thread.__init__(self)

I think it would also work if Publisher.__init__ called
   super(Publisher, self).__init__()
and Publisher is the first base class.

This essay highlights some pitfalls with super() including the one you 
found:
http://fuhm.net/super-harmful/

though it provoked a strong response on python-dev:
http://mail.python.org/pipermail/python-dev/2005-January/050656.html

Kent



More information about the Tutor mailing list