Back
+15 XP
Concept

Generic Classes with Generic[T]

Subclassing `Generic[T]` allows you to build generic data structures (stacks, repositories, response envelopes) that preserve type safety for any contained type 🏛️.

python
from typing import TypeVar, Generic

T = TypeVar('T')

class Box(Generic[T]):
    def __init__(self, content: T):
        self.content = content

    def unwrap(self) -> T:
        return self.content

int_box = Box[int](42)
print(f"Unwrapped content: {int_box.unwrap()} 🏛️")

# 100. Generic Classes with Generic[T] Subclassing `Generic[T]` allows you to build generic data structures (stacks, repositories, response envelopes) that preserve type safety for any contained type 🏛️. ```python from typing import TypeVar, Generic T = TypeVar('T') class Box(Generic[T]): def __init__(self, content: T): self.content = content def unwrap(self) -> T: return self.content int_box = Box[int](42) print(f"Unwrapped content: {int_box.unwrap()} 🏛️") ``` Type checkers understand that `Box[int].unwrap()` returns an `int`, while `Box[str].unwrap()` returns a `str`! 🏛️ --- ### Question What base class enables custom classes to accept type parameters like `MyStack[int]`? 🧠 - [ ] a. `Generic[T]` 🏛️ - [ ] b. `Template[T]` - [ ] c. `Type[T]` - [ ] d. `Any[T]` --- ### Challenge Create `T = TypeVar('T')`. Define `class Storage(Generic[T]): def __init__(self, item: T): self.item = item`. Create `s = Storage[str]('Data')` and print `s.item`. 🎯 <details> <summary>Solution</summary> ```python from typing import TypeVar, Generic T = TypeVar("T") class Storage(Generic[T]): def __init__(self, item: T): self.item = item s = Storage[str]("Data") print(s.item) ``` </details>

Checkpoint

What base class enables custom classes to accept type parameters like `MyStack[int]`? 🧠

Practice

Create `T = TypeVar('T')`. Define `class Storage(Generic[T]): def __init__(self, item: T): self.item = item`. Create `s = Storage[str]('Data')` and print `s.item`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks