问题描述
我最初定义了以下抽象类:
I initially defined the following abstract class:
from abc import ABC, abstractmethod
class Primitive(ABC):
现在,我想创建另一个继承自Primitive的抽象类:
Now I want to create another abstract class that inherits from Primitive:
class InstrumentName(Primitive)
我需要将此类抽象化,因为我最终想要创建以下两个具体的类:
I need this class to be abstract since I ultimately want to create the following two concrete classes:
class CurrencyInstrumentName(InstrumentName)
class MetalInstrumentName(InstrumentName)
我已经阅读了文档并进行了搜索,但是它们主要涉及从抽象类中细分具体的类,或者讨论Python如何处理抽象
I have read the documentation and searched SO, but they mostly pertain to sublcassing concrete classes from abstract classes, or discussing how Python handles abstraction
推荐答案
只是子类,您不需要做任何特殊的事情.
Just subclass, you don't need to do anything special.
仅当实现中不再有abstractmethod
和abstractproperty
对象时,类才变得具体.
A class only becomes concrete when there are no more abstractmethod
and abstractproperty
objects left in the implementation.
让我们说明一下:
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'
在这里,InstrumentName
仍然是抽象的,因为bar
被保留为abstractmethod
.您无法创建该子类的实例:
Here, InstrumentName
is still abstract, because bar
is left as an abstractmethod
. You can't create an instance of that subclass:
>>> InstrumentName()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class InstrumentName with abstract methods bar
子类还可以根据需要添加@abstractmethod
或@abstractproperty
方法.
Subclasses can also add @abstractmethod
or @abstractproperty
methods as needed.
在内部,所有子类继承了强制执行此操作的ABCMeta
元类,并且仅检查该类上是否还有任何@abstractmethod
或@abstractproperty
属性.
Under the hood, all subclasses inherit the ABCMeta
metaclass that enforces this, and it simply checks if there are any @abstractmethod
or @abstractproperty
attributes left on the class.
这篇关于Python3-如何从现有抽象类定义抽象子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!