如何在 Python 中创建没有 getter 的 setter?

How to create a setter without a getter in Python?

class My_Class:
    def __init__(self):
        self._x = 0

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

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

如果我从上面的代码中删除以下getter:

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

代码停止工作。如何创建没有 getter 的 setter?

class My_Class:
    def __init__(self):
        self._x = 0

    @property
    def x(self):
        raise RuntimeError('This property has no getter!')

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

property函数不必作为一个decorator:decorator可以作为函数使用:

class My_Class:
    def _set_x(self, value):
        self._x = value

    x = property(fset=_set_x)  # now value has only a setter

    del _set_x  # optional: delete the unneeded setter function

instance = My_Class()
instance.x= 8  # the setter works

print(instance._x) # the "private" value

print(instance.x) # raises: AttributeError: unreadable attribute

这是我已经提供的替代答案:制作你自己的只写 descriptor

class WriteOnly:
    def __init__(self, private_name):
        self.private_name = private_name

    def __set__(self, obj, value):
        obj.__dict__[self.private_name] = value

    def __get__(self, obj, type=None):
        raise AttributeError('unreadable attribute')


class My_Class:
    x = WriteOnly('_x')

instance = My_Class()
instance.x = 8  # the setter works

print(instance._x) # the "private" value

print(instance.x) # raises: AttributeError: unreadable attribute