【发布时间】:2019-07-11 20:48:35
【问题描述】:
如何将 instance 属性标记为未在基类中实现? (与 this 问题不同,该问题讨论将 class 属性标记为未实现,但也许我没有正确理解基类......)
例如我想要类似的东西
class Base():
def __init__(self):
self.x = NotImplemented
class GoodSub(Base):
def __init__(self, x):
super().__init__()
self.x = x #good
class BadSub(Base):
def __init__(self):
super().__init__()
#forgot to set self.x
good = GoodSub(5)
bad = BadSub(-1)
good.x #returns 5
bad.x #throws error because x not implemented
或者,有没有更好的方法来强制Base 的所有子类在初始化时设置self.x 属性?
【问题讨论】:
-
注意
bad.x不会抛出错误,它会返回NotImplemented类。 -
是的,这正是我想要解决的问题。使用
@propertys 感觉有点笨拙,尤其是如果有很多“抽象实例属性”我想在基类中定义...
标签: python inheritance abstract-class subclass abstract