Do I need setters/getters in python?

zljubisic at gmail.com zljubisic at gmail.com
Mon Jun 8 16:10:57 EDT 2020


Consider this code:


class SetGet:

    _x = 1

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value


class Dynamic:

    x = 1

if __name__ == '__main__':

    a = SetGet()

    print(f'x = {a.x}')
    a.x = 2
    print(f'x = {a.x}')

    a = Dynamic()
    print(f'x = {a.x}')
    a.x = 2
    print(f'x = {a.x}')


Output is the same:

x = 1
x = 2
x = 1
x = 2

If I have public property and I am not doing any transformation with data that is used to sat variable value... do I need a setter/getter at all?


Is there any difference if property "_x" is defined as class property as in the case in SetGet class, or if I have put it in the SetGet inite like:

class SetGet:
    def __init__():
        self._x = 1

(the rest is the same).

When I said "difference", I mean except the fact that in init I can change "_x"'s value at the time of class construction.

Regards


More information about the Python-list mailing list