Python ไม่ต้องประกาศตัวแปร (No Declaration) ตัวแปรสร้างขึ้นตอน Assignment ครั้งแรก
Static vs Dynamic Typing
| Static (C, Java, C#) | Dynamic (Python) |
|---|---|
ต้องประกาศ Type ก่อนใช้ int x; | ไม่ต้องประกาศ Type |
| Compiler เช็ค Type Compile-time | Type ถูก 결정 Runtime |
x = "Hello" → Compile Error | x = "Hello" → OK (x เป็น str) |
ตัวอย่าง Python
>>> a = "Hello" # a ชี้ไป String Object
>>> type(a)
<class 'str'>
>>> a = 10 # a ชี้ไป Integer Object (ตัวเดิมถูก GC)
>>> type(a)
<class 'int'>
>>> a = [1, 2, 3] # a ชี้ไป List Object
>>> type(a)
<class 'list'>
แนวคิด: Variable = Name Tag ผูกกับ Object
- Object มี Type, Value, Identity (id())
- Variable แค่ Label ชี้ไป Object
- Reassign = ย้าย Label ไป Object ใหม่