Do I need setters/getters in python?

Terry Reedy tjreedy at udel.edu
Mon Jun 8 16:27:14 EDT 2020


On 6/8/2020 4:10 PM, zljubisic at gmail.com wrote:
> 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?

No!


-- 
Terry Jan Reedy



More information about the Python-list mailing list