Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Python

functools.singledispatchmethod

Elige el método por el primer argumento posicional tras self o cls.

Versión: Python 3.14; repository image, production runtime not attested

Sintaxis

@functools.singledispatchmethod

Elige el método por el primer argumento posicional tras self o cls.

register añade una variante por tipo y sin registro aplicable se usa la original. Con classmethod se coloca singledispatchmethod por fuera para mantener register accesible.

El entero 15 da 0xf y la cadena 15 da other.

from functools import singledispatchmethod
class Parse:
    @singledispatchmethod
    @classmethod
    def read(cls, arg): return "other"
    @read.register
    @classmethod
    def _(cls, arg: int): return cls.__name__
assert Parse.read(True) == "Parse" and Parse.read("1") == "other"

Ejemplos

import functools
class Formatter:
    @functools.singledispatchmethod
    def show(self, value): return "other"
    @show.register(int)
    def integer(self, value): return hex(value)

f = Formatter()
print(f.show(15), f.show("15"))

Resultado

0xf other

El entero 15 da 0xf y la cadena 15 da other.

Fuentes