why no 'length' method in sequences ?

Alex Martelli aleax at aleax.it
Thu Apr 18 15:47:58 EDT 2002


Terry Reedy wrote:
        ...
> which, only some types had/have methods.  Tuples still do not have
> methods (that I know of).  Strings did not until fairly recently.

Python 2.2.1 (#1, Apr 15 2002, 17:55:14)
[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=2,3,4
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', 
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', 
'__gt__', '__hash__',
'__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__repr__', '__rmul__', '__setattr__', '__str__']
>>>

That's about 20 methods plus static-method __new__.  Of course,
they ARE all special-methods -- maybe that's what you meant.
Only about half are also in type object, by the way -- the others are
specifically added by type tuple.

Special methods are normally invoked via operators, built-in functions,
and/or statements -- e.g., x.__str__() is normally called indirectly via
        print x
or
        str(x)
although of course you're not forbidden from calling one directly:

>>> (5,6,7).__str__()
'(5, 6, 7)'
>>>


This subtle arrangement allows built-ins to potentially "add value" to
(special) methods.  For example, we see that tuples don't define a
method __cmp__.  Despite this, built-in cmp() can still compare two
tuples, by relying on their __eq__ and __lt__ methods.  And vice
versa, if some type defines only __cmp__, a < b can still be obtained,
by relying on that.  So, doing all of your comparisons through operators
or the cmp() built-in gives you better polymorphism than calling the
methods directly.  Similar _potential_ considerations apply in many
other cases, even though the language should not be exploiting all
of them at any given point in time.


Alex




More information about the Python-list mailing list