print " I am " + 10 + "years old " will raise error . but it is ok in many other languages. Java,eg.
回复内容:
因为 Python 禁止跨类型的 (+),它只有
(+): int * int → int
(+): string * string → string
而没有
(+): int * str → ⊤
JavaScript 和 PHP 都允许 (+) 做跨类型的计算,JavaScript 使用 num * str → str,PHP 使用 num * str → num。
The Zen of Python里面有这么一句嘛
Explicit is better than implicit.
Python程序员的常见错误 里面也解释了这句话
只有在数字类型中才存在类型转换 在Python中,一个诸如123+3.145的表达式是可以工作的——它会自动将整数型转换为浮点型,然后用浮点运算。但是下面的代码就会出错了: S = "42" I = 1 X = S + I # 类型错误 这同样也是有意而为的,因为这是不明确的:究竟是将字符串转换为数字(进行相加)呢,还是将数字转换为字符串(进行联接)呢?在Python中,我们认为“明确比含糊好”(即,EIBTI(Explicit is better than implicit)),因此你得手动转换类型: X = int(S) + I # 做加法: 43 X = S + str(I) # 字符串联接: "421"
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn