Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在Python 3中重写属性的抽象设置器_Python 3.x_Properties_Abstract Methods - Fatal编程技术网

Python 3.x 在Python 3中重写属性的抽象设置器

Python 3.x 在Python 3中重写属性的抽象设置器,python-3.x,properties,abstract-methods,Python 3.x,Properties,Abstract Methods,在Python3中,哪种最简单/最具Python风格的方法可以仅覆盖抽象属性的setter?变量3似乎意味着派生类实现者所付出的努力最少。对吗?它有缺点吗 import abc class A1(metaclass=abc.ABCMeta): def __init__(self, x, **kwargs): super().__init__(**kwargs) self._x = x @property def x(self):

在Python3中,哪种最简单/最具Python风格的方法可以仅覆盖抽象属性的setter?变量3似乎意味着派生类实现者所付出的努力最少。对吗?它有缺点吗

import abc


class A1(metaclass=abc.ABCMeta):
    def __init__(self, x, **kwargs):
        super().__init__(**kwargs)
        self._x = x

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

    @x.setter
    @abc.abstractmethod
    def x(self, value):
        self._x = value


class B1(A1):
    @property
    def x(self):
        return super().x

    @x.setter
    def x(self, value):
        print("B1 setter")
        super(B1, self.__class__).x.fset(self, value)

b1 = B1(x=1)
b1.x = 3
print(b1.x)


class A2(metaclass=abc.ABCMeta):
    def __init__(self, x, **kwargs):
        super().__init__(**kwargs)
        self._x = x

    @abc.abstractmethod
    def _get_x(self):
        return self._x

    @abc.abstractmethod
    def _set_x(self, value):
        self._x = value

    x = property(_get_x, _set_x)


class B2(A2):

    def _get_x(self):
        return super()._get_x()

    def _set_x(self, value):
        print("B2 setter")
        super()._set_x(value)

    x = property(_get_x, _set_x)

b2 = B2(x=1)
b2.x = 3
print(b2.x)


class A3(metaclass=abc.ABCMeta):
    def __init__(self, x, **kwargs):
        super().__init__(**kwargs)
        self._x = x

    def _get_x(self):
        return self._x

    @abc.abstractmethod
    def _set_x(self, value):
        self._x = value

    x = property(
        lambda self: self._get_x(),
        lambda self, value: self._set_x(value))


class B3(A3):

    def _set_x(self, value):
        print("B3 setter")
        super()._set_x(value)


b3 = B3(x=1)
b3.x = 3
print(b3.x)

因此,是的,您在其中列出了很多方法-尽管需要更多代码的是变体3,但最严格、最不令人惊讶的方法是变体1-

它可以正常工作,而且可读性很好,没有什么令人惊讶的——而且似乎没有比在那里显式调用
fget
更简单的方法了