Tuesday, June 25, 2013

Why use Python Properties?

The reasoning is here, but in short  "...[t]he answer is, that in [a simple] use case we would not. In fact, we would write thus:
>>> class MyClass(object):
...   x = 0
...
>>> my = MyClass()
>>> my.x = 4
>>> my.x
4

'But!', I can hear you scream, 'there's no encapsulation!'. What will we do if we need to control access to x, make it read-only or do something else to it? Won't we have to refactor everything to the getters and setters that we avoided?

No - we just switch to the property version, add whatever we want, and have not changed the interface one iota! The great thing about properties is not that they replace getters and setters, its that you don't have to write them to future-proof your code. You can start out by writing the simplest implementation imaginable, and if you later need to change the implementation you can still do so without changing the interface. Neat, huh?"