The Python standard library and PEP8
steve at REMOVE-THIS-cybersource.com.au
Mon Apr 20 01:48:04 CEST 2009
On Sun, 19 Apr 2009 13:46:23 -0700, Aahz wrote:
> What makes you think Python is "an OO language"?
The fact that everything in Python is an object is a good hint.
> What kind of OO language allows you to do this:
> def square(x):
> return x*x
> for i in range(10):
> print square(x)
The problem is, I believe, that people wrongly imagine that there is One
True Way of a language being "object-oriented", and worse, that the OTW
is the way Java does it. (If it were Smalltalk, they'd at least be able
to make the argument that Smalltalk invented the perfect OO language and
every change since then was corruption.) This is of course nonsense, but
many people fall for it. "The way I'm used to is the One True Way".
As far as str.len versus len(str), apart from saving one character, I
don't see any advantage to one over the other. It really depends on what
you're used to.
It also depends on whether you see the length of a data structure as a
property of the data, or the result of an operation ("counting") on the
data structure. We often fall into the trap of saying such things as "the
string HAS A length of 42" when what we really mean is "if you count the
elements of the string we find 42 of them". I don't believe that the
relationship between strings and length is a has-a relationship. I
believe it is a property requiring a function (counting) to emerge, and
therefore under OO principles, length should *not* be an attribute and
Java et al are guilty of misuse of OO in making length an attribute.
If you don't agree, consider an analogy: think about what it means to say
that "Fred has a height", compared to "Fred has a left arm". You can
point to Fred's left arm, you can surgically remove it, in principle at
least you could surgically attach a left arm to somebody who didn't have
one. The relationship between "Fred" and "left arm" is most certainly a
"has-a" relationship. But the same isn't true for height: you can't
surgically remove Fred's height, and you can't even point to the part of
Fred that is his height. The length of a string is like height.
(In practice, for speed, Python strings store their length in a field to
avoid having to count it. But that's an optimization, it isn't
fundamental to string length.)
More information about the Python-list