Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

functools.singledispatchmethod

Sceglie il metodo dal primo argomento posizionale dopo self o cls.

Versione: Python 3.14; repository image, production runtime not attested

Sintassi

@functools.singledispatchmethod

Sceglie il metodo dal primo argomento posizionale dopo self o cls.

register aggiunge una variante per tipo e senza registrazione adatta vale l’originale. Con classmethod mettere singledispatchmethod all’esterno per conservare register.

L’intero 15 dà 0xf e la stringa 15 dà 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"

Esempi

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"))

Risultato

0xf other

L’intero 15 dà 0xf e la stringa 15 dà other.

Fonti