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()
Run Code Online (Sandbox Code Playgroud)
但如果我打电话给它,那课AbstractBase
就会提高NotImplementedError
.
我是一只羊,不知道如何继续:-)
您可能会考虑使用abc
Abstract Base Class 模块标记__init__
为抽象,然后继续__init__
从子类调用超类(并且,正如DorElias 建议的,给超类__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()
Run Code Online (Sandbox Code Playgroud)
如果您尝试通过parent = AbstractBase()
或实例化parent = AbstractBase.__new__(AbstractBase)
,则会出现错误:
类型错误:无法使用抽象方法init实例化抽象类 AbstractBase
因此,您已经获得了不可实例化的抽象安全性,但与此同时,您仍然可以通过更改基类构造来更改所有子类构造,这是正确和适当的。
您可以做一些丑陋的事情并检查抽象self
type\xe2\x80\x99s 初始值设定项中的类型以确保它是子类型的:
class AbstractBase (object):\n def __init__ (self):\n if type(self) is AbstractBase:\n raise NotImplementedError\n
Run Code Online (Sandbox Code Playgroud)\n\n我认为更 \xe2\x80\x9cnormal\xe2\x80\x9d 的方法是简单地不公开抽象基本类型并期望用户不要创建它。
\n 归档时间: |
|
查看次数: |
2294 次 |
最近记录: |