Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / Python

typing.Protocol

Opisuje strukturno sučelje za statičku provjeru.

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

Sintaksa

class SizedLabel(Protocol): ...

Opisuje strukturno sučelje za statičku provjeru.

Klasa s odgovarajućim članovima ispunjava ga bez izričitog nasljeđivanja.

Primjer poziva potrebnu metodu, no isinstance s protokolom bez runtime_checkable izaziva TypeError.

Primjeri

from typing import Protocol
class Labelled(Protocol):
    def label(self) -> str: ...
class Item:
    def label(self) -> str:
        return "item"
def show(x: Labelled) -> str:
    return x.label()
print(show(Item()))
try:
    isinstance(Item(), Labelled)
except TypeError:
    print("static protocol")

Rezultat

item
static protocol

Primjer poziva potrebnu metodu, no isinstance s protokolom bez runtime_checkable izaziva TypeError.

Izvori