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

时间:2018-06-19 19:39:56

标签: python setter getter

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

如果我从上面的代码中删除了以下吸气剂:

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

代码停止工作。如何在没有吸气剂的情况下创建二传手?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

property函数不必用作装饰器: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

答案 2 :(得分:0)

这是我已经提供的替代答案:制作自己的只写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
相关问题