Python:重写属性时的意外行为

2024-04-18 11:49:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从包含属性x的类继承,然后通过重写setter使这个属性在子类中成为只读的。如果父类中的__init__使用原始setter,则这不起作用。考虑以下代码。你知道吗

class Parent:
    def __init__(self, x=1):
        # I want the following line to use the setter defined in the Parent
        # class, even when __init__ is called from Child using super.
        self.x = x
        # Other initialization of Parent goes here.

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        """Check that x is non-negative."""
        if value < 0:
            raise ValueError("x must be non-negative.")
        self._x = value


class Child(Parent):

    def __init__(self):
        super().__init__()  # Need this for initialization.

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, value):
        """x can only be written to implicitly by setting y."""
        self._y = value
        self._x = abs(value)

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        raise AttributeError("Illegal access to x")

如果我现在尝试实例化Child,我会得到AttributeError: Illegal access to x,因为当调用行self.x = x时,会调用Childxsetter,而不是Parentxsetter。我怎样才能让它以Pythonic的方式使用Parent的setter呢?你知道吗

要清楚的是,当self.x = ...出现在Parent的方法中时,它应该始终使用Parent中的xsetter,当self.x = ...出现在Child的方法中时,它应该始终使用Child中的xsetter,从而引发异常。你知道吗


Tags: thetoselfchildreturn属性initis
1条回答
网友
1楼 · 发布于 2024-04-18 11:49:12

你知道吗 我设法通过调换工作自己解决了这个问题

self.x = x

Parent.__init__

Parent.x.fset(self, x)

我也可以摆脱

@property
def x(self):
    return self._x

Childif中,我使用@Parent.x.setter,而不是@x.setter。你知道吗

相关问题 更多 >