Do you use the get/set pattern (in Python)?

PythonGetter Setter

Python Problem Overview


Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this.

Why do you use or avoid get/set methods in Python?

Python Solutions


Solution 1 - Python

In python, you can just access the attribute directly because it is public:

class MyClass:

    def __init__(self):
        self.my_attribute = 0  

my_object = MyClass()
my_object.my_attribute = 1 # etc.

If you want to do something on access or mutation of the attribute, you can use properties:

class MyClass:

    def __init__(self):
        self._my_attribute = 0

    @property
    def my_attribute(self):
        # Do something if you want
        return self._my_attribute

    @my_attribute.setter
    def my_attribute(self, value):
        # Do something if you want
        self._my_attribute = value
    

Crucially, the client code remains the same.

Solution 2 - Python

Cool link: Python is not Java :)

> In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. So, don't write getters and setters.

Solution 3 - Python

Here is what Guido van Rossum says about that in Masterminds of Programming > What do you mean by "fighting the language"? > > Guido: That usually means that they're > trying to continue their habits that > worked well with a different language. > > [...] People will turn everything into > a class, and turn every access into an > accessor method,
> where that is really not a wise thing to do in Python; > you'll have more verbose code that is
> harder to debug and runs a lot slower. > You know the expression "You can write > FORTRAN in any language?" You can write Java in any language, too.

Solution 4 - Python

No, it's unpythonic. The generally accepted way is to use normal data attribute and replace the ones that need more complex get/set logic with properties.

Solution 5 - Python

The short answer to your question is no, you should use properties when needed. Ryan Tamyoko provides the long answer in his article Getters/Setters/Fuxors

> The basic value to take away from all this is that you want to strive to make sure every single line of code has some value or meaning to the programmer. Programming languages are for humans, not machines. If you have code that looks like it doesn’t do anything useful, is hard to read, or seems tedious, then chances are good that Python has some language feature that will let you remove it.

Solution 6 - Python

Your observation is correct. This is not a normal style of Python programming. Attributes are all public, so you just access (get, set, delete) them as you would with attributes of any object that has them (not just classes or instances). It's easy to tell when Java programmers learn Python because their Python code looks like Java using Python syntax!

I definitely agree with all previous posters, especially @Maximiliano's link to Phillip's famous article and @Max's suggestion that anything more complex than the standard way of setting (and getting) class and instance attributes is to use Properties (or Descriptors to generalize even more) to customize the getting and setting of attributes! (This includes being able to add your own customized versions of private, protected, friend, or whatever policy you want if you desire something other than public.)

As an interesting demo, in Core Python Programming (chapter 13, section 13.16), I came up with an example of using descriptors to store attributes to disk instead of in memory!! Yes, it's an odd form of persistent storage, but it does show you an example of what is possible!

Here's another related post that you may find useful as well: https://stackoverflow.com/questions/2123585/python-multiple-properties-one-setter-getter

Solution 7 - Python

I had come here for that answer(unfortunately i couldn't) . But i found a work around else where . This below code could be alternative for get .
class get_var_lis: def __init__(self): pass def __call__(self): return [2,3,4] def __iter__(self): return iter([2,3,4]) some_other_var = get_var_lis
This is just a workaround . By using the above concept u could easily build get/set methodology in py too.

Solution 8 - Python

Our teacher showed one example on class explaining when we should use accessor functions.

class Woman(Human):
    def getAge(self):
        if self.age > 30:
            return super().getAge() - 10
        else:
            return super().getAge()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAvery PayneView Question on Stackoverflow
Solution 1 - PythonblokeleyView Answer on Stackoverflow
Solution 2 - PythonmgvView Answer on Stackoverflow
Solution 3 - PythonNick DandoulakisView Answer on Stackoverflow
Solution 4 - PythonMax ShawabkehView Answer on Stackoverflow
Solution 5 - PythonShane C. MasonView Answer on Stackoverflow
Solution 6 - PythonwescpyView Answer on Stackoverflow
Solution 7 - PythonyunusView Answer on Stackoverflow
Solution 8 - PythonsjhstoneView Answer on Stackoverflow