如何在Python中创建没有getter的setter?
如果我从上面的代码中删除以下getter:如何在Python中创建没有getter的setter?,python,setter,getter,Python,Setter,Getter,如果我从上面的代码中删除以下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 代码停止工作。如何在没有getter的情况下创建setter?属性函数不必用作decorator:decorato
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的情况下创建setter?属性函数不必用作decorator:decorator可以用作函数:
@property
def x(self):
return self._x
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
对于我已经提出的问题,这里有一个替代答案:只写你自己的东西
你能解释一下用法吗?也许有另一种方法可以解释为什么del_set_value???@juanpa.arrivillaga是在引入@decorator语法之前如何使用属性的标准食谱。它会在方法成为方法之前删除该方法。正如注释所说,如果您不想在我修改答案中的变量名以适应问题后使用X._set_值或X._set_X,那么它是可选的。
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
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