如何在python中声明要在子类中实现的变量?

斯劳

更新

其实我已经测试了所有的答案,但是我想要的功能仍然无法实现。使用@property强制子类直接声明属性,而不是像self.property = xxx在一个函数中那样。我怎么也能做到这一点?

我的意思是,如果子类__get__之前的属性__set__,那么 raise NotImplementedError


如何在超类中声明应该在子类中实现的变量?

换句话说,我想在超类中声明一个虚拟变量。

class A:

    def a(self):               # perfect!
        raise NotImplementedError("...") 

    b = raise NotImplementedError("...")      #how to declare a variable similar with the function above?
斯潘德

由于 Python 并没有真正的虚拟对象,因此您可以通过显式引发异常来模拟方法的情况,但在变量的情况下,您可以覆盖__init__或使用属性而不是变量。

class A(object):

    def __init__(self, *args, **kwargs):
        if not hasattr(self, 'b'):
            raise NotImplementedError("...")

class B(A):
    b = 3

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章