Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / Python

functools.singledispatchmethod

Vyberie metódu podľa prvého pozičného argumentu za self alebo cls.

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

Syntax

@functools.singledispatchmethod

Vyberie metódu podľa prvého pozičného argumentu za self alebo cls.

register pridá variant pre typ a bez vhodnej registrácie platí pôvodná metóda. S classmethod umiestnite singledispatchmethod navonok, aby zostalo dostupné register.

Číslo 15 dá 0xf a reťazec 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"

Príklady

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

Výsledok

0xf other

Číslo 15 dá 0xf a reťazec 15 dá other.

Zdroje