Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / Python

functools.singledispatchmethod

Bira metodu prema prvom položajnom argumentu iza self ili cls.

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

Sintaksa

@functools.singledispatchmethod

Bira metodu prema prvom položajnom argumentu iza self ili cls.

register dodaje inačicu za tip, a bez odgovarajuće registracije vrijedi izvornik. Uz classmethod postavite singledispatchmethod izvana kako bi register ostao dostupan.

Broj 15 daje 0xf, a niz 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"

Primjeri

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

Rezultat

0xf other

Broj 15 daje 0xf, a niz 15 daje other.

Izvori