抽象基础类:在`__init__.py`中引发NotImplementedError()?

2024-10-01 13:45:52 发布

您现在位置:Python中文网/ 问答频道 /正文

PyCharm警告我Call to __init__ of super class is missed

class AbstractBase(object):
    def __init__(self):
        raise NotImplementedError()

class RealChild(AbstractBase):
    def __init__(self):
        #super(RealChild, self).__init__() ####
        print('do stuff')

child=RealChild()

但是如果我调用它,类AbstractBase将引发{}。在

我是只绵羊,不知道该怎么做:-)


Tags: oftoself警告objectinitisdef
3条回答

您可以考虑using the ^{} Abstract Base Class module__init__标记为抽象,然后继续从子类调用超类__init__(并且,作为DorElias suggested,给超类__init__一个{}的简单实现):

from abc import ABCMeta, abstractmethod


class AbstractBase(object, metaclass=ABCMeta):
    @abstractmethod  # This method must be overridden...
    def __init__(self):
        print("...but can still be called via super by subclasses have shared construction logic")
        pass


class RealChild(AbstractBase):
    def __init__(self):
        super().__init__()  # Won't do anything, UNTIL the day you decide all subclasses of AbstractBase need shared logic
        print('do stuff')


child = RealChild()

{{7}如果你想得到一个

TypeError: Can't instantiate abstract class AbstractBase with abstract methods init

因此,您已经获得了无法实现的抽象安全性,但同时,您仍然可以通过更改基类结构来更改所有子类结构,这是正确和恰当的。在

在抽象类中,将init函数中的异常替换为

pass

此异常用于阻止您初始化抽象类的新实例(它是抽象的,所以您不能) 所以要么用“pass”,要么不听pycharm的话,不要叫super

您可以做一些难看的事情,并检查抽象类型的初始值设定项中的self类型,以确保它是子类型:

class AbstractBase (object):
    def __init__ (self):
        if type(self) is AbstractBase:
            raise NotImplementedError

我认为一个更“正常”的方法是不公开抽象基类型,并期望用户不要创建它。在

相关问题 更多 >