python – Using @property versus getters and setters
python – Using @property versus getters and setters
Prefer properties. Its what theyre there for.
The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesnt prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.
The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesnt for production, without changing the code that uses it. At the same time, you dont have to write getters and setters for everything just in case you might need to better control access later.
In Python you dont use getters or setters or properties just for the fun of it. You first just use attributes and then later, only if needed, eventually migrate to a property without having to change the code using your classes.
There is indeed a lot of code with extension .py that uses getters and setters and inheritance and pointless classes everywhere where e.g. a simple tuple would do, but its code from people writing in C++ or Java using Python.
Thats not Python code.
python – Using @property versus getters and setters
Using properties lets you begin with normal attribute accesses and then back them up with getters and setters afterwards as necessary.