如何写让两个Python抽象类互相实现对方的抽象方法?

问题描述 投票:0回答:2

假设您有抽象类

A1
A2
。它们每个都有一个抽象方法和一个具体方法。

from abc import ABC, abstractmethod

class A0(ABC):
    pass

class A1(A0, ABC):
    def foo(self):
        return 1

    @abstractmethod
    def bar(self):
        raise NotImplementedError()


class A2(A0, ABC):
    @abstractmethod
    def foo(self):
        raise NotImplementedError()
    
    def bar(self):
        return 10

现在你想将它们混合在一起以实现彼此的抽象方法:

class C(A2, A1, A0):
    def all(self):
        return (super().foo(), super().bar())


C().all()

但是上面的代码不起作用,因为我收到以下错误:

TypeError: Can't instantiate abstract class C with abstract method foo

如何创建

C
,以便它可以混合
A1
A2

python inheritance multiple-inheritance method-resolution-order linearization
2个回答
1
投票

我将抽象方法移至A0,并在A1、A2类中只实现了其中一个,然后C将它们都实现了:

from abc import ABC, abstractmethod

class A0(ABC):
    @abstractmethod
    def foo(self):
        raise NotImplementedError()

    @abstractmethod
    def bar(self):
        raise NotImplementedError()

class A1(A0, ABC):
    def foo(self):
        return 1

class A2(A0, ABC):
    def bar(self):
        return 10

class C(A1,A2):
    def all(self):
        return (super().foo(), super().bar())


print(C().all())
# can't instantiate A0,A1,A2, as these have not implemented abstract methods
# print(A1()) # won't work
# print(A2()) # won't work

0
投票

这是一个类似于 Gábor Fekete 的解决方案,只不过抽象方法被提取到新的

ABC
中,以避免更改
A0

from abc import ABC, abstractmethod

class A0(ABC):
    pass

class AbstractFoo(A0, ABC):
    @abstractmethod
    def foo(self):
        raise NotImplementedError()

class AbstractBar(A0, ABC):
    @abstractmethod
    def bar(self):
        raise NotImplementedError()

class A1(AbstractFoo, AbstractBar, A0, ABC):
    def foo(self):
        return 1

class A2(AbstractFoo, AbstractBar, A0, ABC):
    def bar(self):
        return 10

class C(A2, A1, A0):
    def all(self):
        return (super().foo(), super().bar())

C().all()

© www.soinside.com 2019 - 2024. All rights reserved.