【问题标题】:How to declare a variable to be implemented in the subclass in python? [duplicate]如何在python的子类中声明要实现的变量? [复制]
【发布时间】:2017-10-06 07:44:11
【问题描述】:

更新

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

我的意思是,如果子类__get____set__ 之前的属性,那么就提升NotImplementedError


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

也就是说,我想在超类中声明一个虚拟变量。

class A:

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

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

    class A(object):
    
        def __init__(self, *args, **kwargs):
            if not hasattr(self, 'b'):
                raise NotImplementedError("...")
    
    class B(A):
        b = 3
    

    【讨论】:

      【解决方案2】:

      您可以使用 property 装饰器。更多信息,请查看this thread,您可以在此获得详细解答。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        • 2021-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多