What is not objects in Python?

George Sakkis george.sakkis at gmail.com
Mon Sep 29 16:56:06 CEST 2008


On Sep 29, 9:02 am, bearophileH... at lycos.com wrote:

> George Sakkis:
>
> > I don't see the same value in creating a distinction between methods
> > and builtin functions unless the latter are truly generic (and even
> > then I wouldn't mind having them as methods of the base object class,
> > e.g. object.type()). Having a builtin len(x) delegate to x.__len__()
> > seems harder to justify.
>
> I have shown few usage examples of the len() one of the posts in this
> thread. Can you take a look at them and show how you can better
> rewrite them without a len function?
>
> Bye,
> bearophile

You mean this ?

>>> seq = ["aaaa", "bb", "c", "ddd"]
>>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]]
>>> sorted(seq, key=lambda x:x.__len__())
['c', 'bb', 'ddd', 'aaaa']
>>> sorted(seq2, key=lambda x:x.__len__())
[[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]]

Sure, "len" looks better than lambda x:x.__len__(), but the same would
be true if there was an "upper" builtin for the following example:

>>> s = ['a', 'd', 'B', 'C']
>>> s2 = [u'a', u'd', u'B', u'C']
>>> upper = lambda x: x.upper()
>>> sorted(s, key=upper)
['a', 'B', 'C', 'd']
>>> sorted(s2, key=upper)
[u'a', u'B', u'C', u'd']

No difference in principle, just len() happens to be implemented more
often than upper().

George



More information about the Python-list mailing list