Función getattr() de Python
Ejemplo
Obtenga el valor de la propiedad "edad" del objeto "Persona":
class Person:
name = "John"
age = 36
country = "Norway"
x =
getattr(Person, 'age')
Definición y uso
La getattr()
función devuelve el valor del atributo especificado del objeto especificado.
Sintaxis
getattr(object, attribute, default)
Valores paramétricos
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 |
Más ejemplos
Ejemplo
Use el parámetro "predeterminado" para escribir un mensaje cuando el atributo no existe:
class Person:
name = "John"
age = 36
country = "Norway"
x =
getattr(Person, 'page', 'my message')
páginas relacionadas
La función delattr() , para eliminar un atributo
La función hasattr() , para verificar si existe un atributo
La función setattr() , para establecer el valor de un atributo