Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / Python

functools.singledispatchmethod

Izbere metodo po prvem položajnem argumentu za self ali cls.

Različica: Python 3.14; repository image, production runtime not attested

Sintaksa

@functools.singledispatchmethod

Izbere metodo po prvem položajnem argumentu za self ali cls.

register doda različico za tip, brez ustrezne registracije velja izvirnik. Pri classmethod postavite singledispatchmethod na zunanjo stran, da ostane register dostopen.

Število 15 da 0xf, niz 15 pa 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"

Primeri

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

Število 15 da 0xf, niz 15 pa other.

Viri