我不太熟悉抽象类的使用,所以我试图了解我目前使用的一些代码中发生了什么。
在代码中,我有一个基本数据集类,以及从主数据集继承的一些数据集实现,例如:
class dataset(metaclass=abc.ABCMeta):
def __init__():
# implementation of __init__
@abc.abstractmethod
def _some_method(self, ....):
return
class dataset_01(dataset):
def _some_method(self, ....):
# implementation of _some_method for dataset_01, overriding abstract method from base class
我不明白的是,我期待在 dataset_01 中看到对
super().__init__()
的调用:
class dataset_01(dataset):
def __init__(self, length):
super().__init__(...)
没有这样的调用,但是在调试代码时,我注意到在创建 dataset_01 的实例时,尽管缺少 super,但我仍然最终进入了 dataset 的构造函数。
在数据集类中使用metaclass=abc.ABCMeta是否会导致一些自动方法解析,即是否确保基类的
__init__
方法无论如何都被调用?
还是我还漏掉了其他东西?
当你在Python中创建一个子类时,如果该子类没有自己的
__init__()
方法,它将自动继承父类的__init__()
方法。这就是为什么,即使你没有在 super().__init__()
中显式调用 dataset_01
,当你创建 dataset
的实例时,仍然会调用父类 dataset_01
的构造函数。
使用
metaclass=abc.ABCMeta
不会影响此行为。它的主要目的是确保包含此元类的类不能直接实例化(因为它是抽象类),并且它的所有抽象方法必须由任何非抽象子类实现。
总之,您观察到的行为是 Python 中的标准行为,并非特定于抽象类的使用。