在抽象基类中定义@property.setter会给attributeee

2024-05-14 00:25:51 发布

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

抽象基类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)

Tags: selfdatabasereturn定义foovaluedef
1条回答
网友
1楼 · 发布于 2024-05-14 00:25:51

我不知道是否有办法用@property装饰器来完成它,但是如下所示的“手动”完成它似乎是可行的

from abc import ABC, abstractmethod


def reload_data():
    return ['hello']


class Base(ABC):
    @abstractmethod
    def _get_data(self):
        pass

    # Non-abstract.
    def _set_data(self, value):
        self._data = value


class Foo(Base):
    def __init__(self):
        self._data = None

    # Define inherited abstract method.
    def _get_data(self):
        if self._data is None:
            self._data = reload_data()
        return self._data

    data = property(_get_data, Base._set_data)


foo = Foo()
foo.data = ['world']
print(foo.data)  # ['world']

相关问题 更多 >