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

popop
  • 126

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

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

回复
阅读 18.2k
4 个回答
justjavac
  • 47.7k
✓ 已被采纳

python代码:

>>> 3+6
9

>>> "3"+6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't 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 type(s) 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'就可以当作整型来进行计算。

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

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

EasonTang
  • 679

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏