Python getattr() Funzione
Esempio
Ottieni il valore della proprietà "età" dell'oggetto "Persona":
class Person:
name = "John"
age = 36
country = "Norway"
x =
getattr(Person, 'age')
Definizione e utilizzo
La getattr()
funzione restituisce il valore dell'attributo specificato dall'oggetto specificato.
Sintassi
getattr(object, attribute, default)
Valori dei parametri
Parameter | Description |
---|---|
object | Required. An object. |
attribute | The name of the attribute you want to get the value from |
default | Optional. The value to return if the attribute does not exist |
Altri esempi
Esempio
Utilizzare il parametro "predefinito" per scrivere un messaggio quando l'attributo non esiste:
class Person:
name = "John"
age = 36
country = "Norway"
x =
getattr(Person, 'page', 'my message')
Pagine correlate
La funzione delattr() , per rimuovere un attributo
La funzione hasattr() , per verificare se esiste un attributo
La funzione setattr() , per impostare il valore di un attributo