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 è definito
1class Config:
2 debug = True
3 port = 8080
4
# Le istanze possono leggere gli attributi di classe
5config = Config()
# Nomi di attributi come stringhe, decisi a runtime
6attrs = ["debug", "port", "host"]
7for attr in attrs:
# Legge l'attributo per nome; se manca restituisce "Not set" invece di AttributeError
8 value = getattr(config, attr, "Not set")
# Stampa debug: True, port: 8080, host: Not set
9 print(f"{attr}: {value}")

Output

debug: True
port: 8080
host: Not set
Esercitati a digitare questo codice

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

Altri esempi Python di livello 4

← Pratica di digitazione Python