Python - 动态类型
Python 语言的一个突出特性是它是一种动态类型语言。基于编译器的语言如 C/C++、Java 等是静态类型语言。让我们来理解静态类型和动态类型的区别。
在静态类型语言中,每个变量及其数据类型必须在赋值之前声明。任何其他类型的数值编译器都是不可接受的,并会引发编译时错误。
让我们看以下 Java 程序片段 −
public class MyClass {
public static void main(String args[]) {
int var;
var="Hello";
System.out.println("Value of var = " + var);
}
}
这里,var 被声明为 integer 变量。当我们尝试为其赋值字符串值时,编译器会给出以下错误信息 −
/MyClass.java:4: error: incompatible types: String cannot be converted to int
x="Hello";
^
1 error
为什么 Python 被称为动态类型语言?
Python 中的变量只是一个标签或对存储在内存中的对象的引用,而不是一个命名的内存位置。因此,不需要预先声明类型。因为它只是一个标签,可以贴在另一个对象上,该对象可能是任何类型。
在 Java 中,变量的类型决定了它能存储什么以及不能存储什么。在 Python 中,则恰恰相反。这里,数据(即对象)的类型决定了变量的类型。首先,让我们将一个字符串存储到变量中并检查其类型。
>>> var="Hello"
>>> print ("id of var is ", id(var))
id of var is 2822590451184
>>> print ("type of var is ", type(var))
type of var is <class 'str'>
因此,var 是 string 类型。然而,它并非永久绑定。它只是一个标签;可以赋值给任何其他类型的对象,比如 float,它将以不同的 id() 存储 −
>>> var=25.50
>>> print ("id of var is ", id(var))
id of var is 2822589562256
>>> print ("type of var is ", type(var))
type of var is <class 'float'>
或者一个 tuple。现在 var 标签位于一个不同的对象上。
>>> var=(10,20,30)
>>> print ("id of var is ", id(var))
id of var is 2822592028992
>>> print ("type of var is ", type(var))
type of var is <class 'tuple'>
我们可以看到,var 的类型每次引用新对象时都会改变。这就是为什么 Python 是一种 动态类型语言。
Python 的 动态类型特性 使其比 C/C++ 和 Java 更灵活。然而,它容易引发运行时错误,因此程序员需要小心。