python abstract property setter with concrete getter

You'll need a little bit of indirection. Define the setter as you normally would, but have it call an abstract method that does the actual work. Then each child class will need to provide a definition of that method. For example,

class Base(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self):
        self._val = 3

    @property
    def val(self):
        return self._val

    @val.setter
    def val(self, x):
        self._val_setter(x)

    @abc.abstractmethod
    def _val_setter(self, x):
        pass


class Child(Base):

    def _val_setter(self, x):
        self._val = 2*x

Then

>>> c = Child()
>>> print c.val
3
>>> c.val = 9
>>> print c.val
18

How I ended up doing it.

class C(metaclass=ABCMeta):
    @property
    def x(self):
        ...

    @x.setter
    @abstractmethod
    def x(self, val):
        ...

class D(C):
    @C.x.setter
    def x(self, val):
        ...

Tags:

Python