ข้ามไปยังเนื้อหา

Variables & Types

ใน Python คุณกำหนดค่าให้กับชื่อตัวแปรได้เลย — ไม่ต้องประกาศชนิดข้อมูล ชนิดของตัวแปรถูกกำหนดโดยออบเจกต์ที่อ้างถึงในขณะนั้น ไม่ใช่โดยการประกาศ

x = 10 # x อ้างถึง int
x = "hello" # x อ้างถึง str แล้ว — ถูกต้องสมบูรณ์
x = [1, 2, 3] # x อ้างถึง list แล้ว

นี่เรียกว่า dynamic typing ชนิดข้อมูลติดอยู่กับออบเจกต์ ไม่ใช่กับชื่อตัวแปร

Python มีชนิดข้อมูล scalar สี่ชนิดที่คุณจะใช้ในทุกโปรแกรม:

ชนิดตัวอย่างค่าหมายเหตุ
int42, -7, 0ความแม่นยำไม่จำกัด — ไม่มี overflow
float3.14, -0.5ทศนิยม IEEE 754 double precision
str"hello", 'world'ลำดับ Unicode ที่เปลี่ยนแปลงไม่ได้
boolTrue, Falsesubclass ของ int; True == 1, False == 0

ยังมี None — singleton ที่แทนการขาดค่า None มีชนิดข้อมูลของตัวเอง คือ NoneType และมี None เพียงออบเจกต์เดียวในกระบวนการ Python ทั้งหมด ทดสอบด้วย is None เสมอ ไม่ใช่ == None

type() คืนชนิดที่แน่นอนของออบเจกต์ isinstance() ทดสอบว่าออบเจกต์เป็น instance ของชนิดนั้นหรือ subclass ของตัวเอง

age = 30
print(type(age)) # <class 'int'>
print(isinstance(age, int)) # True
print(isinstance(True, int)) # True — bool เป็น subclass ของ int

Python ไม่แปลงชนิดข้อมูลโดยอัตโนมัติ คุณต้องแปลงอย่างชัดเจนโดยใช้ชื่อชนิดข้อมูลเป็นฟังก์ชัน:

n = int("42") # str -> int
f = float("3.14") # str -> float
s = str(100) # int -> str
b = bool(0) # int -> bool -> False

ถ้าแปลงไม่ได้ Python จะ raise ValueError:

int("hello") # ValueError: invalid literal for int()

ออบเจกต์ Python ทุกชิ้นมีการตีความเป็น boolean ที่ใช้ใน if และ while ค่าต่อไปนี้เป็น falsy — ค่าอื่นๆ ทั้งหมดเป็น truthy:

  • False, None
  • ศูนย์: 0, 0.0, 0j
  • container ว่างเปล่า: "", [], {}, (), set()
name = ""
if name:
print("has name")
else:
print("name is empty") # branch นี้ทำงาน
age: int = 30
price: float = 9.99
greeting: str = "Hello"
active: bool = True
nothing = None
print(type(age))
print(type(price))
print(type(greeting))
print(type(active))
print(type(nothing))
x = int("42")
y = float("3.14")
z = str(100)
print(x, y, z)
falsy_values = [0, "", None, False, [], 0.0]
for v in falsy_values:
print(f"bool({v!r}) = {bool(v)}")
Dynamic typing ใน Python หมายความว่าอะไร?
ค่าใดต่อไปนี้เป็น falsy ใน Python?
ควรทดสอบว่าตัวแปรเก็บ None อยู่อย่างไร?
`bool` สืบทอดมาจากอะไรใน Python?