Explanation of list reference

Chris Angelico rosuav at gmail.com
Sun Feb 16 06:24:42 EST 2014


On Sun, Feb 16, 2014 at 9:52 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Ian Kelly <ian.g.kelly at gmail.com>:
>
>>>>> (1).__str__()
>> '1'
>
> Fair enough.
>
> The syntactic awkwardness, then, explains why numbers don't have an
> evolved set of methods (unlike strings).

No; it's more that numbers are more often used with either operators
or polymorphic functions. Yes, you can add strings together with +,
but with numbers, you also subtract them, multiply them (okay, you can
multiply a string by a number, but that kinda counts one to each), and
divide them (some languages let you divide a string by a string, but
Python does that with the .split() method). There are only two types
of string, and arguably one of them is more an array of bytes than it
is a string; but with numbers, you have
int/float/complex/Fraction/Decimal, and rather than create methods
that have to be implemented by each, there are stand-alone functions
instead.

Strings get methods:
>>> "a b c d".count(" ")
3
>>> "asdf".capitalize()
'Asdf'
>>> "asdf".center(20)
'        asdf        '

Numbers get functions:
>>> math.sqrt(100)
10.0
>>> math.sqrt(100.0)
10.0
>>> math.log(1234)
7.1180162044653335

Sometimes the line is blurred:
>>> help(math.trunc)
Help on built-in function trunc in module math:

trunc(x)
    Truncates x to the nearest Integral toward 0. Uses the __trunc__
magic method.

Which could have been done as x.trunc() instead:

>>> 0o1.__trunc__
<built-in method __trunc__ of int object at 0x1E288A30>
>>> 1.0.__trunc__
<built-in method __trunc__ of float object at 0x012AF400>
>>> (1+0j).__trunc__
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    (1+0j).__trunc__
AttributeError: 'complex' object has no attribute '__trunc__'
>>> math.trunc(1+0j)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    math.trunc(1+0j)
TypeError: type complex doesn't define __trunc__ method

But in a lot of cases, it makes good sense to have a single function
that can take many types of number (since, after all, it's possible to
define a lot of functions in terms of the basic operators), whereas
doing them as methods would entail duplicating code.

Partly it's just a matter of expectations. People expect strings to
have more methods and numbers to use more operators, so a string
method is discoverable and an int method is less so. (When was the
last time *you* checked to see what methods an int has?)

ChrisA



More information about the Python-list mailing list