views:

1296

answers:

1

So, I think the code probably explains what I'm trying to do better than I can in words, so here goes:

import abc

class foo(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def bar(self):
        pass


class bar_for_foo_mixin(object):
    def bar(self):
        print "This should satisfy the abstract method requirement"


class myfoo(foo, bar_for_foo_mixin):
    def __init__(self):
        print "myfoo __init__ called"
        self.bar()

obj = myfoo()

The result:

TypeError: Can't instantiate abstract class myfoo with abstract methods bar

I'm trying to get the mixin class to satisfy the requirements of the abstract/interface class. What am I missing?

+2  A: 

Shouldn't the inheritance be the other way round? In the MRO foo currently comes before bar_for_foo_mixin, and then rightfully complains. With class myfoo(bar_for_foo_mixin, foo) it should work.

And I am not sure if your class design is the right way to do it. Since you use a mixin for implementing bar it might be better not to derive from foo and just register it with the 'foo' class (i.e. foo.register(myfoo)). But this is just my gut feeling.

For completeness, here is the documentation for ABCs.

P.S. I am still on Python 2.5 so I cannot test this, apologies if I am wrong.

nikow
Good call, changing the order of inheritance does the trick. P.S. the code was simplified to illustrate a point. My real world scenario is much more complex with lots of potential mixins and lots of myfoos.
mluebke