Skip to main content
 首页 » 编程设计

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

2024年12月31日11hnrainll

下面是一个例子:

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

# 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 方法。

谢谢。

请您参考如下方法:

问题是 double_underscore 属性在 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()