python非抽象方法调用抽象方法

2024-04-24 10:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我举了一个例子:

我定义抽象类的第一个脚本:

# test.py

from abc import ABCMeta, abstractmethod


class A:
    __metaclass__ = ABCMeta

    def __init__(self, a):
        self.x = a
        self.y = 0

    @abstractmethod
    def __foo_1(self):
        pass

    @abstractmethod
    def __foo_2(self):
        pass

    # that is what i'm wondering if it could be possible
    def run(self):
        self.__foo_1()
        self.__foo_2()

在第二个脚本中,我实现了抽象方法:

# test2.py

from test import A


class B(A):
    def __foo_1(self):
        self.y += 1

    def __foo_2(self):
        self.y += 2

因为我确定__foo_1__foo_2必须按这个顺序调用,所以我想编写非抽象方法run来实现这一点(就像test.py)。但似乎不起作用:

b = B(1)
b.run()

>> TypeError: Can't instantiate abstract class B with abstract methods _A__foo_1, _A__foo_2

有什么办法吗?因为我不想每次都重写相同的run-方法。你知道吗

谢谢你。你知道吗


Tags: 方法runfrompytestimportself脚本
2条回答

好吧。。。我找到了我需要的,我只需要把受保护的方法__foo改成普通的方法foo就可以了。你知道吗

问题是双下划线属性在Python中有点神奇。你知道吗

docs

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

因此,不是重写__foo_1,而是得到一个抽象的_A__foo_1()和一个实现的_B__foo_1()

相关问题 更多 >