0

It appears many times while working with Python classes it is quite possible to get the same functionality with getMyAttr() and setMyAtt() methods instead of declaring the class attributes/variables such as self.myVariable

The more I work with OOP the more I tend to use class methods to get and set the attributes. I wonder if a direction I am taking is right and if I am not going to be sorry 10K lines of code later. Please advice!

Popo
  • 2,402
  • 5
  • 33
  • 55
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • Why do you want to use getters/setters instead of just accessing the attributes directly? – BrenBarn Feb 14 '14 at 20:51
  • 3
    You should be using a mixture of direct access and `@property`, as the situation requires. They are syntactically interchangeable for a reason. – roippi Feb 14 '14 at 20:53

1 Answers1

7

You're thinking in the right direction but you should be looking at Python properties to do what you're doing:

 class Foo():
   def __init__(self, x):
     self.__x = x

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

   @x.setter
   def set_x(self, value):
     if(value < 0):
       self.__x = value

Wherein you can nest the "set" logic and the "get" logic (if you're changing how to present it.) This makes calling the value x from the class feel as if you're accessing attributes.

   foo = Foo(-4)
   foo.x
   >>> -4
   foo.x = 3
   foo.x
   >>> -4
   foo.x = -12
   foo.x
   >>> -12
wheaties
  • 35,646
  • 15
  • 94
  • 131