为什么说 Python 是强类型语言?

以为作为脚本语言就是弱类型的……求其中道理!

还有,类型检查的强弱区别(利弊)在哪里?

python代码:

>>> 3+6
9 >>> "3"+6
Traceback most recent call last: File "<stdin>", line 1, in <module>
TypeError: Cant convert int object to str implicitly >>> "3"+"6"
36 >>> "6"-"3"
Traceback most recent call last: File "<stdin>", line 1, in <module>
TypeError: unsupported operand types for -: str and str

javascript代码:

3+6
9 "3"+6
"36" "3"+"6"
"36" "6"-"3"
3

强弱是对类型而言的。
强类型,你有一个值之后这个值是什么类型是确定,比如n=1,n的类型是确定的(字符串),因此你不能在Python做n=3 m=n+1运算。而弱类型就不是这样的,值的类型可以在需要的时候再去确定,比如PHP里面你可以$n=3; $m=$n+1,运算的时候3就可以当作整型来进行计算。

弱类型使用会灵活些,但有时候也会因为这种灵活而带来一些歧义,相比而已,强类型就更严谨了。

我的个人理解是这样的,不知道对不对。

In computer programming, programming languages are often colloquially referred to as strongly typed or weakly typed. In general, these terms do not have a precise definition, but in general a strongly typed language is more likely to generate an error or refuse to compile a program if the argument passed to a function does not closely match the expected type. A very weakly typed language may produce unpredictable results or may perform implicit type conversion instead. On the other hand, a very strongly typed language may not work at all or crash when data of an unexpected type is passed to a function.

http://en.wikipedia.org/wiki/Strong_and_weak_typing

这个回答比较靠谱:

弱类型、强类型、动态类型、静态类型语言的区别是什么?

发表评论

电子邮件地址不会被公开。 必填项已用*标注