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

Classes

class ของ Python ให้ความรู้สึกใกล้เคียง class ของ TypeScript มาก มีทั้ง class, constructor, method และ inheritance ครบ จุดที่ TS developer มักสะดุดมีอยู่สามข้อ:

  1. constructor ชื่อ __init__ ไม่ใช่ constructor
  2. instance method ทุกตัวต้องประกาศ self เป็นพารามิเตอร์แรก เพราะ Python ไม่ฉีด this ให้โดยปริยาย
  3. class attribute ที่แชร์กันทุก instance ประกาศไว้ที่ระดับ class body ไม่ใช่ใน constructor
TypeScript
// TypeScript
class 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);
Python
# Python
class 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" keyword
print(cat.speak())
print(Animal.kingdom)

Python ใช้ syntax แบบ single-inheritance เหมือน TypeScript super().__init__(...) แมปกับ super() ใน TS

TypeScript
// TypeScript
class 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 woof
console.log(rex.fetch("ball")); // Rex fetches the ball!
console.log(rex instanceof Animal); // true
Python
# Python
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()) # Rex says woof
print(rex.fetch("ball")) # Rex fetches the ball!
print(isinstance(rex, Animal)) # True
TypeScript
// TypeScript
class 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
Python
# Python
class 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))
เมธอด constructor ของ Python มีชื่อว่าอะไร?
ใน Python `self` อ้างถึงอะไรภายใน instance method?
class attributes (ที่แชร์ร่วมกันทุก instance) ถูกประกาศที่ไหนใน Python?