您的示例演示了动态输入,而不是弱输入。动态类型通常意味着对象可以存储的数据类型是可变的;任何目标都可以与任何类型的对象保持绑定。与之相反,比如说,C#,它是静态类型的[*]。int i = 5; // Okay.
i = "5"; // Illegal! i can only hold integers.
强类型意味着一旦分配了一个特定类型的值,对象就遵守关于它们如何与其他不同类型的对象交互的严格规则。弱类型意味着这样的规则更加宽松。这并不意味着强类型语言在任何方面都必然优越;它只是一种语言设计选择。
Python被认为是强类型的,因为对象对它们的类型有一个不同的概念。对象之间不兼容的操作会导致错误:>>> 1 + 1 # Add two integers.
2
>>> "1" + "1" # Concatenate two strings.
'11'
>>> 1 + int("1") # Add two integers.
2
>>> "1" + str(1) # Concatenate two strings.
'11'
>>> 1 + "1" # Undefined! Adding integers and strings is meaningless.
Traceback (most recent call last):
File "", line 5, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'
但在PHP中,规则对于可接受的内容要宽松得多。因此,它被认为比其他一些语言更弱类型。$x = 1 + "1"; // x is 2
[*]从技术上讲,从C#4开始,C#是静态类型的,但由于使用了dynamic关键字,因此在每个绑定的基础上使用了opt-in动态类型。现在很多语言都在增加动态能力,模糊界限,所以说“X语言是动态的”和“Y语言是静态的”变得越来越难。它更像是一个滑动标度或光谱,而不是一个二元性质。