如何将抽象类和超类都继承到子类

时间:2019-03-14 17:17:14

标签: python abstract-class multiple-inheritance mixins

我正在尝试将超类的abstact类和超类都继承到一个子类。

下面是我用作示例的代码

from abc import ABC, abstractmethod


class foo(ABC):

    def __init__(self):
        pass

    @abstractmethod
    def bar(self):
        pass

    def item(self):
        a = 1
        b = 2
        c = a + b
        print(c)


class bar_for_foo_mixin(foo):
    def __init__(self):
        foo.__init__(self)
    def bar(self):
        print("This should satisfy the abstract method requirement")
        self.item()

fo = foo()
temp = bar_for_foo_mixin(fo)
temp.bar()

这将引发异常,说明:

Can't instantiate abstract class foo with abstract methods bar

但是,如果我继承子类,则可以使用以下代码正常工作。

from abc import ABC, abstractmethod


class foo(ABC):

    def __init__(self):
        pass

    @abstractmethod
    def bar(self):
        pass

    def item(self):
        a = 1
        b = 2
        c = a + b
        print(c)


class bar_for_foo_mixin(foo):
    def __init__(self):
        foo.__init__(self)
    def bar(self):
        print("This should satisfy the abstract method requirement")
        self.item()


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


obj = myfoo()

你能解释一下我要去哪里吗?

0 个答案:

没有答案