Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Setter and Getter Naming

I'm trying to understand how getters and setters work in python with properties, but I'm confused in the naming convention.

Is there a specific naming standard for the getter and setter? Why do I need to set the returning name of parameter with an "_" (underscore)? If I were to change it to just "self.color" instead of "self._color", the getter and setter no longer work. Also, if I were to change the name of the functions the print function is no longer is executed. Any clarification would be greatly appreciated, thanks!

class FavoriteColor:
    def __init__(self, color):
        self.color = color

    @property
    def color(self):
        print('getter method')
        return self._color

    @color.setter
    def color(self, x):
        print('setter method')
        self._color = x

obj1 = FavoriteColor('blue')

like image 304
dko512 Avatar asked Feb 10 '26 22:02

dko512


1 Answers

If you did this:

@color.setter
def color(self, x):
    self.color = x

Then this setter would call itself repeatedly. There's no difference between obj1.color = 'blue' and self.color = x, they both do the same thing, which is to invoke the setter def color. So with the setter invoking itself recursively, you have an endless recursive loop which will eventually crash your program.

For that purpose you need to actually store the value on some other attribute. Using "_color" for its name is just the rather obvious solution.

Note that using this kind of setter/getter in Python is frowned upon, if your setter/getter doesn't do anything. You can remove them entirely and just plainly set self.color = 'blue' for exactly the same effect as your setter/getter pair currently has. You should only use setters/getters if they do some additional processing. Since the syntax of a plain attribute and a setter/getter are identical, you can even safely transition to using setters/getters later on if you need to (in contrast to, say, Java, where a setter/getter is foo.setBar(...), which is not identical to foo.bar = ... and cannot be transparently substituted later).

like image 155
deceze Avatar answered Feb 12 '26 13:02

deceze