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
If I delete the following getter from the code above:
@property
def x(self):
return self._x
The code stops working. How can I create a setter without a getter?
The property function does not have to be used as a decorator:decorator can be used as a function:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With