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

2024-01-03

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

from abc import ABC, abstractmethod    
class Primitive(ABC):

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

class InstrumentName(Primitive)

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

class CurrencyInstrumentName(InstrumentName)
class MetalInstrumentName(InstrumentName)

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


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

只有当不再有类时,类才会变得具体abstractmethod and abstractproperty实施中留下的对象。

让我们来说明一下:

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'

Here, 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

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

在引擎盖下,所有子类继承ABCMeta强制执行此操作的元类,它只是检查是否有任何@abstractmethod or @abstractproperty留在类上的属性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python3 - 如何从现有抽象类定义抽象子类? 的相关文章

随机推荐