База знанияИзпитен център
BGБългарски
Избери език13

CKTIS / Python

functools.singledispatchmethod

Избира метод по първия позиционен аргумент след self или cls.

Версия: Python 3.14; repository image, production runtime not attested

Синтаксис

@functools.singledispatchmethod

Избира метод по първия позиционен аргумент след self или cls.

register добавя вариант за тип, а без подходяща регистрация действа оригиналът. С classmethod сложете singledispatchmethod отвън, за да остане достъпен register.

Числото 15 дава 0xf, а низът 15 дава 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"

Примери

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

Резултат

0xf other

Числото 15 дава 0xf, а низът 15 дава other.

Източници