No subject
Tue Oct 14 00:29:20 CEST 2008
Python 2.2.
> Furthermore:
>
> >>> range(3.3, 10.3)
> [3, 4, 5, 6, 7, 8, 9]
>
> But:
>
> >>> range('1', '5')
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: an integer is required
>
> Now I note that strings don't have __int__, so I guess the int type handles
> int('42') itself using special knowledge about strings.
That's correct. int() knows how to convert strings:
>>> print int.__doc__
int(x[, base]) -> integer
Convert a string or number to an integer, if possible. A floating
point argument will be truncated towards zero (this does not include
a string representation of a floating point number!) When
converting a string, use the optional base. It is an error to
supply a base when converting a non-string.
> I suppose that's to
> keep strings from seeming to be numbers, since the nb_int slot fills in the
> number_methods.
>
> And:
>
> >>> class zero(object):
> ... def __int__(self): return 0
> ...
> >>> range(zero(), 5)
> [0, 1, 2, 3, 4]
>
> So, is there any general practice, (even if it's not universal)? Do Python
> functions usually tend to coerce their arguments into the types they're
> expecting? I'm guessing the answer is no...
More information about the Cplusplus-sig
mailing list