CKTIS / Python
functools.singledispatchmethod
Wählt die Methode nach dem ersten Positionsargument hinter self oder cls.
Version: Python 3.14; repository image, production runtime not attested
Syntax
@functools.singledispatchmethodWählt die Methode nach dem ersten Positionsargument hinter self oder cls.
register ergänzt eine Typvariante, ohne passende Registrierung gilt das Original. Bei classmethod muss singledispatchmethod außen stehen, damit register verfügbar bleibt.
Die Zahl 15 ergibt 0xf und die Zeichenkette 15 ergibt 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"
Beispiele
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"))
Ergebnis
0xf other
Die Zahl 15 ergibt 0xf und die Zeichenkette 15 ergibt other.