【问题标题】:How to create a setter without a getter in Python? [duplicate]如何在 Python 中创建没有 getter 的 setter? [复制]
【发布时间】:2018-11-28 20:29:22
【问题描述】:
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?

【问题讨论】:

  • 你能解释一下用法吗?也许有另一种方法

标签: python setter getter


【解决方案1】:

property 函数不必用作装饰器:装饰器可以用作函数:

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

【讨论】:

  • 为什么del _set_value??
  • @juanpa.arrivillaga 这是在引入@decorator 语法之前如何使用property 的标准食谱。它甚至在成为方法之前就删除了该方法。正如评论所说,如果您不想拥有X._set_value(或X._set_x,在我修改答案中的变量名称以适应问题之后),它是可选的。
【解决方案2】:
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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 2022-07-23
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      相关资源
      最近更新 更多