Steven D'Aprano steve+comp.lang.python at
Sat Nov 1 02:06:56 CET 2014

Gregory Ewing wrote:

> Seymore4Head wrote:
>> The course is free.  You can't beat the price.  It is only for a few
>> more weeks.
> But if it's teaching you things that are blatantly wrong
> in relation to Python, it may be doing more harm than
> good.

Like all good Pythonistas[1], we hate Java and think that getter/setter
methods are pointless. But come on, they're not *wrong*, as in incorrect.
They do the job they're supposed to do, at the expense of an awkward
interface. Using properties is *exactly the same as Java getters/setters*,
except that the interface is less awkward.

And there are times when using getters and setters is the right choice.
Properties should only be used for quite lightweight calculations, because
attribute access is supposed to be fast. If your calculation is complex,
time-consuming or might fail, using a property is a bad idea and you should
use an explicit getter method, possibly with a setter if needed.

There are lots of things in Python which are written as getter methods or
functions, rather than attributes or properties. E.g.:

py> (23).bit_length()
py> len("hello world!")  # calls __len__ method

Files have quite a few examples. fileno, isatty and writable could all be
written as read-only properties, and seek/tell could be written as a
file.position property. But they're not, they're written as methods.

[1] Except for Jythonistas, who are allowed to enjoy using Java.


More information about the Python-list mailing list