![](/img/trans.png)
[英]Is there an "Addable" protocol or abstract base class in Python? If not how would one define it?
[英]Python3 - How does one define an abstract subclass from an existing abstract class?
我最初定义了以下抽象类:
from abc import ABC, abstractmethod
class Primitive(ABC):
现在我想创建另一个继承自 Primitive 的抽象类:
class InstrumentName(Primitive)
我需要这个类是抽象的,因为我最终想要创建以下两个具体类:
class CurrencyInstrumentName(InstrumentName)
class MetalInstrumentName(InstrumentName)
我已经阅读了文档并搜索了 SO,但它们主要涉及从抽象类中继承具体类,或讨论 Python 如何处理抽象
只是子类,你不需要做任何特别的事情。
只有在实现中不再有abstractmethod
和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'
在这里, 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
或@abstractproperty
方法。
在ABCMeta
,所有子类都继承了强制执行此操作的ABCMeta
元类,它只是检查类中是否还有任何@abstractmethod
或@abstractproperty
属性。
正如@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
另一种方式:
...
class InstrumentName(Primitive, metaclass=abc.ABCMeta):
def is_tuba(self):
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.