Correct way to use accessors in Python?

python, python-2.7

Solution

In Python we generally avoid getters and setters. Just have a `.speed` attribute:

class Car(object):
    speed = 0

    def __init__(self):
        self.speed = 100

See Python is not Java for motivations and more pitfalls to avoid:

In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. So, don't write getters and setters.

Use `property` when you have a genuine need to execute code when getting, setting or deleting an attribute. Validation, caching, side effects, etc. all are fair use-cases for properties. Just don't use them until necessary.

Problem

Is this how you would define a class "Car" with attribute "Speed" in Python? My background is in Java, and it seems one does not use get/set methods in Python. ``` class Car(object): def __init__(self): self._speed = 100 @property def speed(self): return self._speed @speed.setter def speed(self, value): self._speed = value ```

Original source

Related problems