gpt4 book ai didi

python - 抽象基类 : raise NotImplementedError() in `__init__.py` ?

转载 作者:太空狗 更新时间:2023-10-29 21:39:29 26 4
gpt4 key购买 nike

PyCharm 警告我未调用父类(super class)的 __init__

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

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

child=RealChild()

但是如果我调用它,AbstractBase 类将引发 NotImplementedError

我是一只羊,不知道如何进行:-)

最佳答案

您可能会考虑 using the abc Abstract Base Class module__init__ 标记为抽象,然后继续从子类调用父类(super class) __init__ (并且,作为 DorElias suggested ,给父类(super class) __init__ pass 的简单实现):

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()

如果您尝试通过 parent = AbstractBase()parent = AbstractBase.__new__(AbstractBase) 实例化,您将收到错误消息:

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

因此,您获得了不可实例化的抽象安全性,但与此同时,您仍然准备好通过更改基类构造来更改所有子类构造,这是正确和适当的。

关于python - 抽象基类 : raise NotImplementedError() in `__init__.py` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32372108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com