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 被声明为一个整数变量。当我们尝试为其分配字符串值时,编译器会给出以下错误消息 -
/MyClass.java:4: error: incompatible types: String cannot be converted to int
x="Hello";
^
1 error
x="Hello";
^
1 error
为什么 Python 被称为动态类型?
Python 中的变量只是一个标签,或对存储在内存中的对象的引用,而不是命名的内存位置。因此,不需要 type 的先前声明。因为它只是一个标签,所以它可以放在另一个对象上,可以是任何类型。
在 Java 中,变量的类型决定了它可以存储什么,不能存储什么。在 Python 中,情况正好相反。在这里,数据类型(即 object)决定了变量的类型。首先,让我们在变量中存储一个字符串 in check its type。
>>> 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 是字符串类型。但是,它不是永久绑定的。它只是一个标签;并且可以分配给任何其他类型的对象,比如 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'>
或元组。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 是一种动态类型语言。
与 C/C++ 和 Java 相比,Python 的动态类型特性使其非常灵活。但是,它很容易出现运行时错误,因此程序员必须小心