Python3 - 如何从现有的抽象类定义抽象子类?

Abh*_*nan 5 python oop inheritance abstract-class python-3.x

我最初定义了以下抽象类:

from abc import ABC, abstractmethod    
class Primitive(ABC):
Run Code Online (Sandbox Code Playgroud)

现在我想创建另一个继承自Primitive的抽象类:

class InstrumentName(Primitive)
Run Code Online (Sandbox Code Playgroud)

我需要这个类是抽象的,因为我最终想要创建以下两个具体类:

class CurrencyInstrumentName(InstrumentName)
class MetalInstrumentName(InstrumentName)
Run Code Online (Sandbox Code Playgroud)

我已阅读文档并搜索了SO,但它们主要涉及从抽象类中提升具体类,或讨论Python如何处理抽象

Mar*_*ers 11

只是子类,你不需要做任何特别的事情.

只有在实现中没有更多abstractmethodabstractproperty对象时,类才变得具体.

让我们来说明一下:

from abc import ABC, abstractmethod    
class Primitive(ABC):
    @abstractmethod
    def foo(self):
        pass

    @abstractmethod
    def bar(self):
        pass

class InstrumentName(Primitive):
    def foo(self):
        return 'Foo implementation'
Run Code Online (Sandbox Code Playgroud)

在这里,InstrumentName仍然是抽象的,因为它bar被留作了abstractmethod.您无法创建该子类的实例:

>>> InstrumentName()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class InstrumentName with abstract methods bar
Run Code Online (Sandbox Code Playgroud)

子类还可以根据需要添加@abstractmethod@abstractproperty方法.

引擎盖下,所有子类继承ABCMeta,强制执行这个元类,它只是检查是否有任何@abstractmethod@abstractproperty留在类的属性.

  • 所以我应该忽略 PyCharm 的警告,即我没有提供 InstrumentName 的具体实现吗? (4认同)

Jer*_*101 9

正如 @MartijnPieters 所写,您不需要为 Python 做任何特殊的事情,但 PyCharm 会警告:

类 InstrumentName 必须实现所有抽象方法

抑制该警告的一种方法是:

import abc

class Primitive(abc.ABC):
    @abc.abstractmethod
    def foo(self):
        pass

# noinspection PyAbstractClass
class InstrumentName(Primitive):
    def is_tuba(self):
        return False
Run Code Online (Sandbox Code Playgroud)

其他方式:

...

class InstrumentName(Primitive, metaclass=abc.ABCMeta):
    def is_tuba(self):
        return False
Run Code Online (Sandbox Code Playgroud)

  • pylint 也会抱怨。你的第二个建议对两者都适用。 (4认同)