Classes
Classes: familiar concept, explicit self
Section titled “Classes: familiar concept, explicit self”Python classes feel very similar to TypeScript classes. You have class, a constructor, methods, and inheritance. The main things that trip up TS developers are:
- The constructor is named
__init__, notconstructor. - Every instance method must declare
selfas its first parameter — Python does not injectthisimplicitly. - Class attributes (shared across all instances) are declared at class body level, not inside the constructor.
Defining a class
Section titled “Defining a class”// 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
Section titled “Inheritance”Python uses the same single-inheritance syntax as TypeScript. super().__init__(...) maps to super() in 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 and static methods
Section titled “Class methods and 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()) # 2Try it
Section titled “Try it”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)…