python中的抽象类+mixin+多重继承 [英] Abstract class + mixin + multiple inheritance in python

查看:37
本文介绍了python中的抽象类+mixin+多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我认为代码可能比文字更能解释我想要做的事情,所以这里是:

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()

结果:

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

我试图让 mixin 类满足抽象/接口类的要求.我错过了什么?

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

推荐答案

继承不应该反过来吗?在 MRO 中,foo 当前位于 bar_for_foo_mixin 之前,然后理所当然地抱怨.使用 class myfoo(bar_for_foo_mixin, foo) 它应该可以工作.

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.

而且我不确定您的课程设计是否正确.由于您使用 mixin 来实现 bar,因此最好不要从 foo 派生,而只需将其注册到 'foo' 类(即 foo.register(myfoo)).但这只是我的直觉.

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.

为了完整起见,这里是 ABC 文档.

For completeness, here is the documentation for ABCs.

这篇关于python中的抽象类+mixin+多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆