Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a setter without a getter in Python? [duplicate]

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?

like image 443
Matheus Schaly Avatar asked Jul 30 '26 00:07

Matheus Schaly


1 Answers

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
like image 141
zvone Avatar answered Jul 31 '26 14:07

zvone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!