Search code examples
pythonpropertiespython-decoratorsgetter-setter

Python get and set methods versus @property decorator


I am exploring decorators in Python, and as a person who came to Python from other languages, I am a bit confused about the purpose of @property and its @xxx.setter brother. In Java and C++ get_xxx() and set_xxx() are usually the way to organize encapsulation. In Python we have these two decorators, which require specific syntax, and name matching in order to work. How is @property better than get-set methods?

I have checked this post and still, what are the advantages of @property besides the availability of the += operator?


Solution

  • The best part of using property for an attribute is that you don't need it.

    The philosophy in Python is that classes attributes and methods are all public, but by convention - when you prefix their name with a single "_"

    The mechanism behing "property", the descriptor protocol, allows one to change a previous dumb plain attribute into an instrumented attribute, guarded with code for the getter and setter, if the system evolves to a situation where it is needed.

    But by default, a name attribute in a class, is just a plain attribute. You do person.name = "Name"- no guards needed, no setting method needed nor recommended. When and if it one needs a guard for that (say, to capitalize the name, or filter on improper words), whatever code uses that attribute needs no change: with the use of property, attribute assignment still takes place with the "=" operator.

    Other than that, if using "=" does not look prettier than person.set_name("Name") for you, I think it does for most people. Of course, that is subjective.