0

I have been programming OOP concepts mostly in Java and C++, and recently I have come to use Python. For what I know Python does not necessarly has private variables in their classes, so a programmer can access them directly. For example if I have:

class Whatever:
    #constructor
    def __init__(self,x):
        self.x=x

so a programmer can easily modify the value of x like doing this:

w=Whatever(4)
w.x=6

in this point I was wondering if it would be really necessary to use a setter method like:

setW(self,x)
     self.x=x

is it not the last one a redundancy on the code? I have seen some Python books that strive to do that, but for me it seems pointless, is it necessary?

djechlin
  • 59,258
  • 35
  • 162
  • 290
Little
  • 3,363
  • 10
  • 45
  • 74
  • The original and main goal of setter and getter is stability of your API. If you need to change the internal, you don't break any code. In python we have a very nice way to do it: `@property`. If you need to change something latter, not a problem you can fix it with `@property`. (Using explicit method for getter/setter can have a interest if the computing time is important or have a side-effect. People will assume that dotted attribute access is quick and side-effect free) – Cld Aug 31 '14 at 14:49

3 Answers3

3

One reason comes automatically to my mind: Input validation.

What happens if Whatever.x should be a date but was set to an integer? Some class design requires this kind of validations and this is the perfect way to do it:

class Whatever:

    #constructor
    def __init__(self):
        self._x=None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        if isinstance(value, datetime): #silly example
            self._x = value
        else:
            raise ValueError('Was expecting a date')

That being said, it's not considered very pythonic to have getters and setters for every class data. Some variables that doesn't require this kind of protection can be accessed normally through the instance interface.

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
  • The goal is more for keeping the API stable than to made validation. If you change the way you need to stock data internally for some reason (for exemple integer value in millionth of mars orbital period :)) you can still have input and output using datetime object. – Cld Aug 31 '14 at 14:54
0

Python allows arbitrary members to be added to classes, so having the set method provides an additional check to make typos more obvious:

class Whatever:
    def __init__(self,v):
        self.some_value = v
    def setSomeValue(v):
        self.some_value = v 

w=Whatever(4)
w.some_valu = 6 # No error!
w.setSomeValu(6) # Error
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • thanks, but I am not pretty sure if that is a good reason, because in Python it is not really needed to put attributes in a private fashion – Little Aug 31 '14 at 13:14
  • @Little: Ok, I wasn't trying to make a point that the members should be private, so I've taken the `__` out of the name. – Vaughn Cato Aug 31 '14 at 13:17
  • Such typos can also be caught without making all accesses more ugly and verbose. For example via `__slots__` or a linter. –  Aug 31 '14 at 13:24
  • `__` prefix is __NOT__ private. Is goal is to provide name collision in subclassing (as explain by Raymond Hettinger, python core developer, in this video https://www.youtube.com/watch?feature=player_detailpage&v=HTLu2DFOdTg#t=2006) – Cld Aug 31 '14 at 14:34
0

Getters/Setters in OOP are mainly to maintain the encapsulation concept and for doing access control, input validation, triggers upon, and many other operations on the object's internal variables, this is a concept in OOP design, it applies to all programming languages.

You can always define public member variables in (supposedly) any programming language, but a good OOP design should not expose any of the internal implementation details to the outer world, a class should only expose what's required and should strictly control the access to it and validate the input.

For more information you can check this Programmers Stack Exchange question, the information there apply to OOP in general.

Community
  • 1
  • 1
mpcabd
  • 1,813
  • 15
  • 20
  • allright, but anybody could manipulate a code in a "bad" way even with the variables set to private; also for what I know encapsulation is a way to make a code more readable instead of saying "get away from this part of the code"; maybe that is why Python does not support strong encapsulation – Little Aug 31 '14 at 13:17
  • In Python sure you can easily be bad and manipulate the code, no one can stop you from "harming" the implementation if you really want to. That also applies to Java/.NET if you fiddle around with reflection, and you can easily manipulate the memory in C/C++, but that doesn't stop you from writing good-design code. – mpcabd Aug 31 '14 at 13:21
  • 2
    Encapsulation and information hiding can easily achieved through `@property` which has nicer syntax. –  Aug 31 '14 at 13:22
  • Surely you should use the [`@property` not the `getX`, `setX`](http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters) Java style. – mpcabd Aug 31 '14 at 13:28
  • The original and main goal of encapsulation are not hiding your internal and protection your code, the goal is evolution thru API stability. You need to change the method use for stocking your date internally ? Well you need to change ALL code you made usage of it. With getter/setter, not a problem. Well in Python too but with a lot nicer method: @property – Cld Aug 31 '14 at 14:44