Saltar al contenido principal
🔒 Modo vista previa. Las primeras quince lecciones de Foundations son gratis; esta es Pro. Inicia un trial de 7 días para desbloquear el editor, las pistas AI y el resto del programa. Tarjeta requerida, cancela cuando quieras en Dashboard.Iniciar trial de 7 días →
← CursosSenior Deep-DivesModule 11 · Decorator patterns at scalefunctools.singledispatchmethod — type dispatch when there's a self in the waypredict153 / 161
+150 XP
Tarea
📝 **Tarea:** Predecir la salida de 5 líneas. Una clase `Formatter` tiene un método `format` enviado por el tipo del SEGUNDO argumento (el método singledispatch maneja el auto-salto). Las entradas de prueba cubren int / list / dict / unmatched float (cae por defecto) / bool (que hereda de int → rutas al controlador int, el mismo problema que sr-116). 📋 Implemente la función anterior. Las pruebas se ejecutan automáticamente. 💡 **Pista:** Vuelve a leer la teoría si te quedas atascado.
Predice la salida

Lee el código con atención

from functools import singledispatchmethod


class Formatter:
    @singledispatchmethod
    def format(self, value: object) -> str:
        return f"unknown: {value!r}"

    @format.register
    def _(self, value: int) -> str:
        return f"int: {value}"

    @format.register
    def _(self, value: list) -> str:
        return f"list of {len(value)}"

    @format.register
    def _(self, value: dict) -> str:
        return f"dict with {len(value)} keys"


f = Formatter()
print(f.format(42))
print(f.format([1, 2, 3]))
print(f.format({"a": 1, "b": 2}))
print(f.format(3.14))
print(f.format(True))

¿Qué imprimirá el programa? Escribe aquí:

💬 Discusión

Sé el primero en hacer una pregunta o compartir un consejo.
Inicia sesión para unirte a la discusión. Leer es gratis.
Cargando discusión…