我想在我班上所有的混合罐上调用相同的方法。这是两个变体:
class MixinA(object):
def get_id(self):
return "A"
class MixinB(object):
def get_id(self):
return "B"
class Base(object):
def get_id(self):
for base_class in inspect.getmro(self.__class__):
return ",".join(base_class.get_id())
class Instance(MixinA, MixinB, Base):
pass
class MyTestCase(unittest.TestCase):
def test_multiple_mixin_methods(self):
"""
Sadly, we cannot call all mixin methods.
:return:
"""
ids = set(Instance().get_id())
print(ids)
assert ids == {"A", "B"}
可悲的是,这失败了。我只得到“ A”。我想要一个包含“ A”和“ B”的列表,顺序无所谓。
我在这里做错什么了吗?
非常感谢
您需要调用超级。super调用MRO中的下一个方法,因此您将调用A =>B。您不需要Base类。
class MixinA(object):
def get_id(self):
return "A", super(MixinA, self).get_id()
class MixinB(object):
def get_id(self):
return "B"
class Instance(MixinA, MixinB):
pass
首先,Instance().get_id()
将will调用,A.get_id()
然后对super的调用将调用MRO中的下一个方法B
更新
class MixinA(object):
def get_id(self):
return "A"
class MixinB(object):
def get_id(self):
return "B"
class Base(object):
def get_id(self):
return set([base_class.get_id(self) for base_class in inspect.getmro(self.__class__)[2:-1]])
class Instance(Base, MixinA, MixinB):
pass
不像之前的mixins独立。在此示例中,您需要在MRO中首先使用基类
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句