Interface

3 snippets across 2 stacks - Python, TypeScript

PYPython

Abstract Base Classes

PY · Classes & OOP
Syntax
from abc import ABC, abstractmethod
class Base(ABC):
    @abstractmethod
    def method(self): ...
Example
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...

class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius

    def area(self) -> float:
        return 3.14159 * self.radius ** 2

# shape = Shape()  # TypeError: can't instantiate abstract class
circle = Circle(5)
print(f"Area: {circle.area():.2f}")
Output
Area: 78.54

Note Abstract classes cannot be instantiated directly. Subclasses must implement all @abstractmethod methods or they will also be abstract.

Protocols (Structural Typing)

PY · Classes & OOP
Syntax
from typing import Protocol
class Drawable(Protocol):
    def draw(self) -> None: ...
Example
from typing import Protocol

class Saveable(Protocol):
    def save(self, path: str) -> None: ...

class Document:
    def save(self, path: str) -> None:
        print(f"Saved to {path}")

def backup(item: Saveable, dest: str) -> None:
    item.save(dest)

backup(Document(), "/tmp/doc.txt")
Output
Saved to /tmp/doc.txt

Note Protocols enable duck-typing with static type checking. Classes do not need to explicitly inherit from the Protocol; they just need matching methods.

TSTypeScript

Interface Declaration

TS · Interfaces
Syntax
interface Name {
  property: Type;
  method(param: Type): ReturnType;
}
Example
interface Product {
  id: string;
  name: string;
  price: number;
  getDisplayPrice(): string;
}

const laptop: Product = {
  id: "prod_001",
  name: "Developer Laptop",
  price: 1299,
  getDisplayPrice() {
    return `$${this.price.toFixed(2)}`;
  },
};
Output
// laptop.getDisplayPrice() → "$1299.00"

Note Interfaces define the shape of objects. They are structurally typed - any object with the right shape satisfies the interface, no explicit 'implements' needed for plain objects.

Frequently asked questions

How does Python handle interface?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Abstract Base Classes" snippet in Python uses `from abc import ABC, abstractmethod`.
Which code does the Python example use?
The "Abstract Base Classes" snippet uses `from abc import ABC, abstractmethod`, from the Classes & OOP section of the Python cheat sheet.
Which stacks cover "interface" on this page?
Python, TypeScript. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Abstract Base Classes": Abstract classes cannot be instantiated directly. Subclasses must implement all @abstractmethod methods or they will also be abstract.