Python 是「動態強型別」語言:變數無需宣告型別 (動態),但型別檢查嚴格、不允許隱式轉換 (強型別)。本文透過實例剖析變數繫結、型別變更、記憶體模型與與弱型別/靜態語言的差異。
i = 12
print(i) # 12
# i 直接賦值即建立,無需宣告型別
但變數必須先賦值 (繫結) 才能使用:
i = 1
print(i + j) # NameError: name 'j' is not defined
不同於 BASIC/JS 等弱型別語言會隱式初始化為 0/undefined。
i = 1
print(i, type(i), id(i)) # 1 140123...
i = 10000000000
print(i, type(i), id(i)) # 10000000000 (Python 3 統一為 int) 140124...
i = 1.1
print(i, type(i), id(i)) # 1.1 140125...
i 只是「標籤」貼在不同物件上。id() 回傳物件記憶體位址,每次賦值指向新物件。i = 10
j = 'ss'
print(i + j) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
必須顯式轉換:
print(str(i) + j) # '10ss'
print(i + int(j)) # 若 j 為數字字串
對比弱型別 (JS/PHP/Perl) 會嘗試隱式轉換,產生不可預期結果。
變數名 (名稱空間) 物件 (堆積)
i ──────────────────→ PyLongObject(1) refcount=1
PyLongObject(10000000000) refcount=1
PyFloatObject(1.1) refcount=1
| 特性 | Python | C# (靜態) | C# 4.0+ dynamic |
|---|---|---|---|
| 變數宣告 | 無需 | 必須 | 可選 (dynamic) |
| 型別變更 | 允許 | 禁止 | 允許 |
| 隱式轉換 | 無 | 數值擴展 | 執行期解析 |
| 型別檢查時機 | 執行期 | 編譯期 | 執行期 |
typing) + 靜態檢查工具 (mypy, pyright) 獲得編譯期保護。Python 的動態強型別設計,在靈活性與安全性之間取得絕佳平衡。