getattr con valore predefinito in Python
Livello 4177 battiture
Questo usa getattr() con valore predefinito per accedere in sicurezza agli attributi degli oggetti.
Codice Python
# Una classe con due attributi di classe; host non è definito1class Config:2 debug = True3 port = 80804 # Le istanze possono leggere gli attributi di classe5config = Config()# Nomi di attributi come stringhe, decisi a runtime6attrs = ["debug", "port", "host"]7for attr in attrs: # Legge l'attributo per nome; se manca restituisce "Not set" invece di AttributeError8 value = getattr(config, attr, "Not set") # Stampa debug: True, port: 8080, host: Not set9 print(f"{attr}: {value}")Output
debug: True port: 8080 host: Not set
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.
"× 10=× 5,× 4:× 3(× 3)× 3{× 2}× 2[× 1]× 1