The Python standard library and PEP8
Carl Banks
pavlovevidence at gmail.com
Sun Apr 19 16:43:46 EDT 2009
On Apr 19, 11:41 am, Emmanuel Surleau <emmanuel.surl... at gmail.com>
wrote:
> First off, it's pretty commonplace in OO languages. Secondly, given the
> number of methods available for the string objects, it is only natural to
> assume that dir("a") would show me a len() or length() or size() method.
> Having to use a function for such a mundane operation feels unnatural and
> not OO.
My advice in this situation is to think of len() as an operator that
has the syntax of a regular function. Apart from not having special
syntax, len() is no different from any other operator. It has an
associated method, __len__(), that allows objects to customize their
behavior when the operator is applied to them.
As to why they made len() and operator, it is really just a language
design decision. By making len() into a function, rather than a
method, GvR was essentially saying, "Determining length of a sequence
is a common and familiar enough operation that it deserves status
above a mere method call, even if we don't have a special syntax for
it."
I am not, mind you, arguing either for or against len being an
operator (I don't really think it matters much either way); I'm just
saying there is a rationale behind it.
Carl Banks
More information about the Python-list
mailing list