I have a python property like this:
class Foo:
@property
def maxInputs(self):
return self._persistentMaxInputs.value
@maxInputs.setter
def maxInputs(self, value):
self._persistentMaxInputs.value = value
Currently, the value of maxInputs
can be get and set by everyone.
However, I want to allow everyone to get the value of the maxInputs
, but it should only be set inside of the Foo
class.
So is there a way to declare a property with a private setter and a public getter?
The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.
Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.
Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.
The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.
Python has no privacy model. Using underscores is only a convention, there is no access control.
If you don't want the 'public' API to include a sett, then just remove the setter from your class and assign to self._persistentMaxInputs.value
in your class code directly. You can make it a function if you want to limit the number of locations that need to remember this:
def _setMaxInputs(self, value):
self._persistentMaxInputs.value = value
You can of course make that a separate property
object, but then you'd have to forgo the decorator syntax:
def _maxInputs(self, value):
self._persistentMaxInputs.value = value
_maxInputs = property(None, _maxInputs)
but now at least you can use self._maxInputs = value
in your class code. This doesn't really offer that much of a syntax improvement however.
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