Little
Little

Reputation: 3477

set methods in Python, are they necessary?

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?

Upvotes: 0

Views: 168

Answers (3)

Vaughn Cato
Vaughn Cato

Reputation: 64308

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

Upvotes: 0

mpcabd
mpcabd

Reputation: 1807

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.

Upvotes: 0

Paulo Bu
Paulo Bu

Reputation: 29794

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.

Upvotes: 3

Related Questions