Classes
Classes: แนวคิดที่คุ้นเคย แต่ self ต้องเขียนชัดเจน
หัวข้อที่มีชื่อว่า “Classes: แนวคิดที่คุ้นเคย แต่ self ต้องเขียนชัดเจน”class ของ Python ให้ความรู้สึกใกล้เคียง class ของ TypeScript มาก มีทั้ง class, constructor, method และ inheritance ครบ จุดที่ TS developer มักสะดุดมีอยู่สามข้อ:
- constructor ชื่อ
__init__ไม่ใช่constructor - instance method ทุกตัวต้องประกาศ
selfเป็นพารามิเตอร์แรก เพราะ Python ไม่ฉีดthisให้โดยปริยาย - class attribute ที่แชร์กันทุก instance ประกาศไว้ที่ระดับ class body ไม่ใช่ใน constructor
การนิยามคลาส
หัวข้อที่มีชื่อว่า “การนิยามคลาส”// TypeScriptclass Animal { static kingdom: string = "Animalia"; // class attribute
name: string; sound: string;
constructor(name: string, sound: string) { this.name = name; this.sound = sound; }
speak(): string { return `${this.name} says ${this.sound}`; }
toString(): string { return `Animal(name=${this.name})`; }}
const cat = new Animal("Cat", "meow");console.log(cat.speak());console.log(Animal.kingdom);# Pythonclass Animal: kingdom: str = "Animalia" # class attribute (shared)
def __init__(self, name: str, sound: str) -> None: self.name = name # instance attributes self.sound = sound
def speak(self) -> str: return f"{self.name} says {self.sound}"
def __repr__(self) -> str: return f"Animal(name={self.name!r})"
cat = Animal("Cat", "meow") # no "new" keywordprint(cat.speak())print(Animal.kingdom)Inheritance
หัวข้อที่มีชื่อว่า “Inheritance”Python ใช้ syntax แบบ single-inheritance เหมือน TypeScript super().__init__(...) แมปกับ super() ใน TS
// TypeScriptclass Dog extends Animal { constructor(name: string) { super(name, "woof"); }
fetch(item: string): string { return `${this.name} fetches the ${item}!`; }}
const rex = new Dog("Rex");console.log(rex.speak()); // Rex says woofconsole.log(rex.fetch("ball")); // Rex fetches the ball!console.log(rex instanceof Animal); // true# Pythonclass Dog(Animal): def __init__(self, name: str) -> None: super().__init__(name, "woof")
def fetch(self, item: str) -> str: return f"{self.name} fetches the {item}!"
rex = Dog("Rex")print(rex.speak()) # Rex says woofprint(rex.fetch("ball")) # Rex fetches the ball!print(isinstance(rex, Animal)) # TrueClass methods และ static methods
หัวข้อที่มีชื่อว่า “Class methods และ static methods”// TypeScriptclass Counter { private static count: number = 0;
static increment(): void { Counter.count++; }
static getCount(): number { return Counter.count; }}
Counter.increment();Counter.increment();console.log(Counter.getCount()); // 2# Pythonclass Counter: _count: int = 0 # underscore = "private" by convention
@classmethod def increment(cls) -> None: cls._count += 1
@classmethod def get_count(cls) -> int: return cls._count
Counter.increment()Counter.increment()print(Counter.get_count()) # 2ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”class Animal: kingdom: str = "Animalia"
def __init__(self, name: str, sound: str) -> None: self.name = name self.sound = sound
def speak(self) -> str: return f"{self.name} says {self.sound}"
def __repr__(self) -> str: return f"Animal(name={self.name!r})"
class Dog(Animal): def __init__(self, name: str) -> None: super().__init__(name, "woof")
def fetch(self, item: str) -> str: return f"{self.name} fetches the {item}!"
rex = Dog("Rex")print(rex.speak())print(rex.fetch("ball"))print(f"Is Animal? {isinstance(rex, Animal)}")print(f"Kingdom: {Animal.kingdom}")print(repr(rex))Loading Python runtime (first run only)…