Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python property with public getter and private setter

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?

like image 246
MorgoZ Avatar asked Feb 09 '17 12:02

MorgoZ


People also ask

Can getters and setters be private?

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.

Should getters and setters be public or private?

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.

Do you use getters and setters in python?

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.

What is the benefit of using properties with getters and setters?

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.


1 Answers

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.

like image 93
Martijn Pieters Avatar answered Sep 25 '22 05:09

Martijn Pieters