python中的抽象类+ mixin +多重继承 [英] Abstract class + mixin + multiple inheritance in python
问题描述
所以,我认为代码可能用语言解释了我想做得更好的事情,所以去了:
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屋!