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 被宣告為一個整數變數。當我們嘗試為它分配一個字串值時,編譯器會給出以下錯誤訊息:

/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字串型別。但是,它不是永久繫結的。它只是一個標籤;並且可以分配給任何其他型別的物件,例如浮點數,它將以不同的 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 是一種動態型別語言

Python 的動態型別特性使其與C/C++ 和 Java 相比更加靈活。但是,它容易出現執行時錯誤,因此程式設計師必須小心。

廣告