CKTIS / Python
System typów
Obiekt ma typ określający obsługiwane operacje, a adnotacja parametru nie wymusza typu podczas wywołania.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
type(value)
isinstance(value, Base)
len(value)Obiekt ma typ określający obsługiwane operacje, a adnotacja parametru nie wymusza typu podczas wywołania.
type(x) podaje konkretny typ, isinstance uwzględnia też podklasy. len korzysta z protokołu __len__, więc własna klasa może obsłużyć tę operację niezależnie od dziedziczenia po list.
Shelf daje 3, True jest instancją int, ale ma konkretny typ bool. Liczba 12 nie obsługuje len i zgłasza TypeError.
class Sized:
def __len__(self): return 2
assert len(Sized())==2 and not isinstance(Sized,list)
assert type(True) is bool and issubclass(bool,int)
class Invalid:
def __len__(self): return -1
try: len(Invalid())
except ValueError: pass
else: raise AssertionError
Przykłady
class Shelf:
def __len__(self):
return 3
def size(value: list) -> int:
return len(value)
print(size(Shelf()), isinstance(True, int), type(True) is int)
try:
size(12)
except TypeError as error:
print(type(error).__name__)
Wynik
3 True False TypeError
Shelf daje 3, True jest instancją int, ale ma konkretny typ bool. Liczba 12 nie obsługuje len i zgłasza TypeError.