Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

functools.partialmethod

Definiuje w klasie deskryptor wariantu metody z ustalonymi argumentami.

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

Składnia

functools.partialmethod(func, /, *args, **keywords)

Definiuje w klasie deskryptor wariantu metody z ustalonymi argumentami.

Wiązanie deskryptora przekazuje do jego __get__, a dla funkcji wywoływalnej bez deskryptora wstawia self przed zapamiętanymi argumentami. W 3.14 pozycje Placeholder można zostawić do późniejszego wypełnienia.

enable wiąże True z metodą set konkretnego Switch.

from functools import partialmethod, Placeholder
class Gauge:
    def pair(self, left, right):
        return self, left, right
    right_zero = partialmethod(pair, Placeholder, 0)
g = Gauge()
assert g.right_zero(3) == (g, 3, 0)

Przykłady

import functools
class Switch:
    def set(self, on): self.on = on
    enable = functools.partialmethod(set, True)
    disable = functools.partialmethod(set, False)

s = Switch()
s.enable()
print(s.on)
s.disable()
print(s.on)

Wynik

True
False

enable wiąże True z metodą set konkretnego Switch.

Źródła