抽象基类Base
有一个名为data
的@abstractmethod
,它也是@property
问题:有没有办法在Base
类中定义属性setter data.setter
,这样我们就不必在所有子类中重复定义setter方法(即Foo
)
在ABC中定义data.setter
时显示AttributeError的代码
from abc import ABC, abstractmethod
def reload_data():
return ['hello']
class Base(ABC):
@property
@abstractmethod
def data(self):
pass
@data.setter # <----- AttributeError if this is defined here
def data(self, value):
self._data = value
class Foo(Base):
def __init__(self):
self._data = None
@property
def data(self):
if self._data is None:
self._data = reload_data()
return self._data
# @data.setter # <----- Defining it here avoids AttributeError, but
# def data(self, value): causes code repetition in all the subclasses of Base
# self._data = value
foo = Foo()
foo.data = ['world']
print(foo.data)
我不知道是否有办法用
@property
装饰器来完成它,但是如下所示的“手动”完成它似乎是可行的相关问题 更多 >
编程相关推荐