Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ?

Diez B. Roggisch deets at nospam.web.de
Thu Sep 4 13:19:20 CEST 2008


> Of course, I know that while I'm fresh, I've a good knowledge of the
> code, and anything else, I will be able to avoid such stupid errors;
> however, I'm afraid of the times when I'm tired, when I have to put my
> hands on the code of someone else, and so on.
> 
> Please, understand that I'm not stating that python is wrong... after
> all, if it is wrong, I can move to a language like Java, which has a
> different approach on it. I'm really very interested in reading past
> discussion on it, if they are available.

This has not much to do with the question of setters and getters. Because in
your code you could write

def setX(self, x):
    self.y = x

def getX(self):
    return self.x

So the error occurs in the same way.

What you are essentially asking is: why is python dynamic instead of static? 

Because *that* is what is the difference. In a static language, you need to
declare first what you want to be available, e.g. which variables and
methods are available and such.

Of course then the compiler (or whoever evaluates the static declarations)
can puke on you if you attempt a stunt like the one you describe.

Python (and other languages such as Ruby, Javascript) chose other. They give
you the freedom to add instance variables (or even methods) at will, with
the cost of the occasional error like the above.

OTOH, Java makes me write soooo much more code that me becoming tired and
doing some stupid mistake (and there are lots of them doable in static
languages as well, otherwise no C/C++ or Java-program would crash....)
becomes much more likely....YMMV.

Diez





More information about the Python-list mailing list