In a nutshell: because that's what the spec says. That's kind of a useful mindset to get into anyway. ;-)
Now, why does the spec say so? There are only a finite number of types a function can accept as valid input. The int
function tries to cover two different kinds of use cases:
- convert a string representation of an integer into an actual
int
- cast a
float
value to an int
, truncating it*
The third use case, "convert the string representation of a floating point number to an int
" is not covered by the spec, because the language designers decided not to cover it. Which seems like a reasonable decision to make, since they needed to draw the line somewhere on what types the function would and wouldn't accept. The string representation of a floating point number should be parsed by float
, not int
.
* Actually: any object that has an __int__
method, but lets keep it simple.
As a counter example, in PHP you can try to cast any string to an int
, and it will try to give you the best match:
php > echo (int)'3.14';
3
php > echo (float)'3.14';
3.14
php > echo (int)'3 little pigs';
3
php > echo (int)'there are 3 little pigs';
0
Which, quite honestly, is rather insane behaviour, especially that last one. Python has a strict(er) type system; if you're trying to parse a string as an int
, it must be a perfectly valid representation of an integer number, not merely something that somewhere contains something that can be interpreted as a number.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…