CKTIS / Python
functools.singledispatchmethod
Wybiera metodę według typu pierwszego argumentu pozycyjnego po self lub cls.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
@functools.singledispatchmethodWybiera metodę według typu pierwszego argumentu pozycyjnego po self lub cls.
register dodaje wariant dla typu, a bez pasującej rejestracji działa metoda pierwotna. Przy łączeniu z classmethod umieść singledispatchmethod na zewnątrz, aby zachować dostęp do register.
Liczba 15 daje 0xf, a napis 15 daje 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"
Przykłady
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"))
Wynik
0xf other
Liczba 15 daje 0xf, a napis 15 daje other.