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

Python ขั้นสูง — ภาพรวม

คุณรู้พื้นฐานของ Python แล้ว — ตัวแปร ฟังก์ชัน คลาส collections และ async ระดับขั้นสูงคือจุดที่ปรัชญาการออกแบบของ Python เปล่งประกาย นี่คือเครื่องมือที่ทำให้โค้ดเบส Python ขนาดใหญ่อ่านง่าย เร็ว และดูแลรักษาได้

ถ้าคุณมาจาก TypeScript คุณมีสัญชาตญาณที่แข็งแกร่งเกี่ยวกับ types, generics, decorators, และการทดสอบแบบมีโครงสร้างอยู่แล้ว โมดูลนี้จะแมปสัญชาตญาณเหล่านั้นโดยตรงกับสิ่งเทียบเท่าใน Python และชี้ให้เห็นจุดที่ Python มีความสามารถพิเศษที่ไม่มีคู่ขนานใน TS

บทเรียนแนวคิดหลักคู่ขนานใน TS
Typing & ProtocolsProtocol, TypeVar, TypedDict, Optional/UnionStructural interfaces, generics, mapped types
Dataclasses@dataclass, frozen, field()Class + interface hybrid, records
Metaclasses & Descriptors__get__/__set__, การสืบทอด typeไม่มีคู่เทียบ — ฟีเจอร์เฉพาะ Python
itertools & functoolschain, groupby, lru_cache, partialLodash / Array methods
Pattern Matchingmatch/case กับ structural patternsswitch + destructuring
pytest เชิงลึกFixtures, parametrize, assertionsJest: beforeEach, it.each, expect
Profilingtimeit, cProfile, การอ่าน statsNode --prof, console.time

ระบบ type ของ Python เป็นแบบ opt-in และ runtime-invisible — เช่นเดียวกับ type ใน TypeScript ที่หายไปหลัง compilation ความต่างคือ annotations ของ Python ยังคงอยู่เป็น metadata ที่สามารถ inspect ได้ ซึ่งตรงนี้เองที่ dataclasses, Protocol, และ TypedDict ใช้ประโยชน์

TypeScript
// TypeScript — types are a compiler concern
interface Shape {
area(): number;
}
// Generics are erased at runtime
function first<T>(arr: T[]): T {
return arr[0];
}
Python
# Python — types are annotations (not enforced)
from typing import Protocol, TypeVar
class Shape(Protocol):
def area(self) -> float: ...
T = TypeVar('T')
def first(arr: list[T]) -> T:
return arr[0]
print(first([10, 20, 30])) # 10

แต่ละบทเรียนเป็นไปตามรูปแบบเดียวกัน:

  1. TS analogy ก่อน — ยึดกับสิ่งที่คุณรู้อยู่แล้ว
  2. กลไกของ Python — syntax และ semantics จริง
  3. Interactive playground (เมื่อแนวคิดนั้น self-contained)
  4. PyOnly callouts — สิ่งที่ไม่มีคู่เทียบใน TS
  5. Quiz — ทดสอบความเข้าใจอย่างรวดเร็ว

เรียนตามลำดับ หรือข้ามไปยังบทเรียนที่เกี่ยวข้องกับโปรเจกต์ปัจจุบันของคุณได้เลย

โมดูล Python ใดที่ให้ `Protocol`, `TypeVar`, และ `TypedDict`?
Type hints ของ Python ถูก enforce ที่ runtime โดยค่าเริ่มต้นหรือไม่?