Función Python hasattr()
Funciones integradas de Python3
hasattr()Es una función integrada en Python que se utiliza para comprobar si un objeto tiene el atributo especificado.
hasattr()Devuelve un valor booleano que indica si el objeto contiene el atributo especificado. Esto es muy útil al trabajar con atributos dinámicos o cuando se necesita comprobar primero si un atributo existe.
Definición de términos: hasattr 是 has attribute(有属性)的缩写。
Sintaxis básica y parámetros
Formato de sintaxis
hasattr(object, name)
Descripción de parámetros
- Parámetro object:
- Tipo: cualquier objeto
- Descripción: el objeto a comprobar.
- Parámetro name:
- Tipo: cadena
- Descripción: nombre del atributo.
Descripción de la función
- Valor de retorno: Devuelve un valor booleano
TrueoFalse。
Ejemplos
Ejemplo 1: Uso básico
Ejemplo
class Person:
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# Comprueba si el atributo existe
print(hasattr(p, "name")) # Salida: True
print(hasattr(p, "age")) # Salida: True
print(hasattr(p, "gender")) # Salida: False
# Comprueba el método
print(hasattr(p, "name")) # Salida: True
print(hasattr(p, "walk")) # Salida: False
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# Comprueba si el atributo existe
print(hasattr(p, "name")) # Salida: True
print(hasattr(p, "age")) # Salida: True
print(hasattr(p, "gender")) # Salida: False
# Comprueba el método
print(hasattr(p, "name")) # Salida: True
print(hasattr(p, "walk")) # Salida: False
Resultado esperado de la ejecución:
True True False True False
Análisis del código:
- hasattr() comprueba si el objeto tiene el atributo especificado.
Ejemplo 2: Combinado con getattr
Ejemplo
# Obtener atributo de forma segura
class Config:
def __init__(self):
self.debug = True
self.port = 8080
config = Config()
# Comprobar primero y luego obtener
if hasattr(config, "debug"):
print(f"debug: {config.debug}")
if hasattr(config, "timeout"):
print(f"timeout: {config.timeout}")
else:
print("timeout no existe, se usa el valor predeterminado")
# Salida: timeout no existe, se usa el valor predeterminado
# Comprobación dinámica
attrs = ["debug", "port", "host"]
for attr in attrs:
if hasattr(config, attr):
print(f"{attr}: {getattr(config, attr)}")
class Config:
def __init__(self):
self.debug = True
self.port = 8080
config = Config()
# Comprobar primero y luego obtener
if hasattr(config, "debug"):
print(f"debug: {config.debug}")
if hasattr(config, "timeout"):
print(f"timeout: {config.timeout}")
else:
print("timeout no existe, se usa el valor predeterminado")
# Salida: timeout no existe, se usa el valor predeterminado
# Comprobación dinámica
attrs = ["debug", "port", "host"]
for attr in attrs:
if hasattr(config, attr):
print(f"{attr}: {getattr(config, attr)}")
Resultado de la ejecución:
Al ejecutarlo en el entorno real se mostrará el resultado de la comprobación.
hasattr()A menudo se usagetattr()en combinación.
Funciones integradas de Python3
Otras extensiones