Question

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!

Était-ce utile?

La solution

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top