在Python 3中仅覆盖抽象属性的setter的最简单/最pythonic方法是什么?变体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)
答案 0 :(得分:0)
所以,是的,你在那里列出了很多方法 - 虽然那个需要更多代码的方法是你的变种3,但是最直接的,最不令人惊讶的方式就是你的变种1 -
它只是有效,并且完全可读,没有惊喜 - 而且似乎没有比在那里明确调用fget
更简单的方法。