Pattern Type Guard in Python
Livello 5508 battiture
Questo usa TypeGuard per creare funzioni di restringimento del tipo per una gestione più sicura delle union.
Codice Python
# Importa TypeGuard (Python 3.10+) e Union per le annotazioni di tipo1from typing import TypeGuard, Union2 # class Cat definisce un gatto con metodo meow3class Cat: # meow restituisce il suono del gatto4 def meow(self) -> str:5 return "Meow!"6 # class Dog definisce un cane con metodo bark7class Dog: # bark restituisce il suono del cane8 def bark(self) -> str:9 return "Woof!"10 # is_cat è una funzione type guard per Cat11def is_cat(animal: Union[Cat, Dog]) -> TypeGuard[Cat]: # Restituisce True se animal è Cat, restringe il tipo12 return isinstance(animal, Cat)13 # is_dog è una funzione type guard per Dog14def is_dog(animal: Union[Cat, Dog]) -> TypeGuard[Dog]: # Restituisce True se animal è Dog, restringe il tipo15 return isinstance(animal, Dog)16 # make_sound usa type guard per chiamate sicure di metodi17def make_sound(animal: Union[Cat, Dog]) -> str: # Dopo is_cat, il type checker sa che animal è Cat18 if is_cat(animal): # Si può chiamare meow() in sicurezza19 return animal.meow() # Dopo is_dog, il type checker sa che animal è Dog20 elif is_dog(animal): # Si può chiamare bark() in sicurezza21 return animal.bark() # Fallback per tipi sconosciuti22 return "Unknown"23 # Test con istanza di Cat24print(make_sound(Cat()))# Test con istanza di Dog25print(make_sound(Dog()))Output
Meow! Woof!
Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice Python e quante volte compaiono.
(× 17)× 17:× 12_× 7,× 6"× 6-× 5[× 5]× 5>× 5