2

Should methods inside a class use property/setter accessors, a la "add_to_field" or should they access the private variables directly a la "subtract from field"?

class Example(object):
    def __init__(self, field):
        self._field = field

    @property
    def field(self):
        return self._field

    @field.setter
    def field(self, field):
        self._field = field

    def add_to_field(self, something):
        self.field += something

    def subtract_from_field(self, something):
        self._field += something

How about if the setter didn't purely set the variable, but performed something else, such as logging. Is this bad style?

    @field.setter
    def field(self, field):
        log.logger.debug("Field set to %r", field)
        self._field = field

Currently my code is a mixture of both. Not sure what direction to refactor in.

1
  • 5
    In your initial example, you shouldn't be using a property at all. Just use normal attribute access. Commented Apr 17, 2013 at 7:45

1 Answer 1

3

The main reason to avoid the use of getters and setters are to avoid potential infinite recursion (your setter call your method foo which sets the objects, which call foo, etc.).

Otherwise, it is better to always call the getter/setter in the sense it will ensure your program data stays consistent.

My advice would be: use your getter/setter all the time. If you start having complex setters at one point and the first point becomes a problem, then you should try to rethink your code to keep them simple. An additional method could refactor all the heavy work done in the setters.

If your getter/setter are exactly "return value" and "assign value to a variable", then you just should not define any getter or setter. A nice point in Python is that the day you will need getter or setter, you will be able to do it totally transparently. This is the reason where, in C++ for instance, it is sometimes considered as good practice to always access attributes through getters and setters even if these are just "dummy" functions.

To sum up: I would go with the add_to_field style.

Sign up to request clarification or add additional context in comments.

1 Comment

"... in C++ for instance, it is sometimes considered as good practice to always access attributes through getters and setters even if these are just "dummy" functions." The C++ Core Guidelines actually advise against the practice of trivial getters and setters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.