【问题标题】:Python NotImplementedError for instance attributes实例属性的 Python NotImplementedError
【发布时间】: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 属性?

编辑:link to related question

【问题讨论】:

  • 注意bad.x不会抛出错误,它会返回NotImplemented类。
  • 是的,这正是我想要解决的问题。使用@propertys 感觉有点笨拙,尤其是如果有很多“抽象实例属性”我想在基类中定义...

标签: python inheritance abstract-class subclass abstract


【解决方案1】:

使用类装饰器和描述符的一种解决方案(__get__ 方法):

def abstract_variables(*args):
    class av:
        def __init__(self, error_message):
            self.error_message = error_message

        def __get__(self, *args, **kwargs):
            raise NotImplementedError(self.error_message)

    def f(klass):
        for arg in args:
            setattr(klass, arg, av('Descendants must set variable `{}`'.format(arg)))
        return klass

    return f


@abstract_variables('x', 'y')
class Base:
    def __init__(self):
        pass

class Derived(Base):
    x = 10


b = Base()
d = Derived()
print(d.x)    # prints 10
print(d.y)    # raises NotImplementedError

打印:

10
Traceback (most recent call last):
  File "main.py", line 28, in <module>
    print(d.y)
  File "main.py", line 7, in __get__
    raise NotImplementedError(self.error_message)
NotImplementedError: Descendants must set variable `y`

【讨论】:

  • 我更喜欢这种方法,而不是我支持的 @property 方法。确保您使用functools.wraps,以便更好地进行自省。
  • @AdamSmith 但是我应该wrap() 做什么?我像现在一样返回klass
【解决方案2】:

我会考虑将x 设为属性。

class Base():
    def __init__(self):
        self.__x = None
        self.__x_is_set = False
    @property
    def x(self):
        if not self.__x_is_set:
            raise NotImplementedError('Descendents from Base must set x')
        else:
            return self.__x
    @x.setter
    def x(self, value):
        self.__x = value
        self.__x_is_set = True


class GoodSub(Base):
    def __init__(self):
        super().__init__()
        self.x = 5

class BadSub(Base):
    def __init__(self):
        super().__init__()
        pass

class AlsoBad(Base):
    def __init__(self):
        super().__init__()
        self.__x = 5  # sets the attribute, but not through the property
>>> g, a, b = GoodSub(), BadSub(), AlsoBad()
>>> g.x
5
>>> a.x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in x
NotImplementedError: Descendents from Base must set x
>>> b.x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in x
NotImplementedError: Descendents from Base must set x

【讨论】:

  • 你不能用hasattr(self, '__x')代替__x_is_set来简化代码吗?
  • @norok2 否,因为对于所有这些子类实例assert hasattr(self, '__x')super().__init__() 创建该属性。
  • 你只是没有在基类中定义它
猜你喜欢
  • 2013-11-18
  • 2011-11-24
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 2015-03-22
  • 2018-06-12
  • 1970-01-01
相关资源
最近更新 更多