本文介绍了Python3-如何从现有抽象类定义抽象子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

仅当实现中不再有abstractmethodabstractproperty对象时,类才变得具体.

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-如何从现有抽象类定义抽象子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 07:05