当我们说一种语言是动态类型和静态类型时,这意味着什么?
当前回答
静态类型:在编译时执行的类型检查。
静态类型语言的真正含义是:
必须指定变量的类型 变量只能引用特定类型的对象* 值的类型检查将在编译时执行,任何类型检查都将在此时报告 将在编译时分配内存来存储该特定类型的值
静态类型语言的例子有C、c++、Java。
动态类型:在运行时执行的类型检查。
动态类型语言的真正含义是:
不需要指定变量的类型 同一个变量可以引用不同类型的对象
Python、Ruby都是动态类型语言的例子。
*一些对象可以通过类型转换分配给不同类型的变量(在C和c++等语言中非常常见的做法)
其他回答
静态类型语言:每个变量和表达式在编译时就已经知道了。
(int;A在运行时只能接受整型值)
例如:C, c++, Java
动态类型语言:变量可以在运行时接收不同的值,它们的类型在运行时定义。
(var;A可以在运行时取任何类型的值)
例如:Ruby, Python。
不幸的是,术语“动态类型”具有误导性。所有语言都是静态类型的,类型是表达式的属性(而不是一些人认为的值的属性)。然而,有些语言只有一种类型。这些被称为单一类型语言。这种语言的一个例子是无类型lambda演算。
在无类型lambda演算中,所有的项都是lambda项,对一个项执行的唯一操作是将它应用到另一个项。因此,所有的操作总是导致无限递归或lambda项,但永远不会发出错误信号。
However, were we to augment the untyped lambda calculus with primitive numbers and arithmetic operations, then we could perform nonsensical operations, such adding two lambda terms together: (λx.x) + (λy.y). One could argue that the only sane thing to do is to signal an error when this happens, but to be able to do this, each value has to be tagged with an indicator that indicates whether the term is a lambda term or a number. The addition operator will then check that indeed both arguments are tagged as numbers, and if they aren't, signal an error. Note that these tags are not types, because types are properties of programs, not of values produced by those programs.
这样做的单一类型语言称为动态类型语言。
JavaScript、Python和Ruby等语言都是单一类型的。同样,JavaScript中的typeof操作符和Python中的type函数的名称具有误导性;它们返回与操作数相关的标记,而不是操作数的类型。类似地,c++中的dynamic_cast和Java中的instanceof不做类型检查。
下面是一个对比Python(动态类型)和Go(静态类型)如何处理类型错误的例子:
def silly(a):
if a > 0:
print 'Hi'
else:
print 5 + '3'
Python在运行时执行类型检查,因此:
silly(2)
运行完全正常,并产生预期的输出Hi。只有当有问题的行被击中时才会引发错误:
silly(-1)
生产
不支持'int'和'str'的操作数类型
因为相关的行已经被执行了。
另一方面,Go在编译时进行类型检查:
package main
import ("fmt"
)
func silly(a int) {
if (a > 0) {
fmt.Println("Hi")
} else {
fmt.Println("3" + 5)
}
}
func main() {
silly(2)
}
上述文件将无法编译,并出现以下错误:
无效的操作:"3" + 5(不匹配的类型字符串和int)
静态类型
在运行前检查类型,以便更早地捕获错误。
Examples = c++
动态类型
在执行期间检查类型。
示例= Python
甜蜜和简单的定义,但符合需求: 静态类型语言将类型绑定到整个作用域的变量(Seg: SCALA) 动态类型语言将类型绑定到变量引用的实际值。