CKTIS / Python
hasattr()
Executa de facto a leitura do atributo e interceta AttributeError.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
hasattr(object, name, /)Executa de facto a leitura do atributo e interceta AttributeError.
False significa que toda a leitura terminou com AttributeError. Uma classe com __getattr__ pode resolver a falha da leitura e nesse caso obtém-se True. Na instância a função de leitura gera essa exceção, daí False. Na classe lê-se o próprio objeto property sem chamar a função de leitura, daí True.
As outras exceções propagam-se.
class Sensor:
@property
def sample(self): raise AttributeError("offline")
class Recovered(Sensor):
def __getattr__(self, name): return None
assert hasattr(Recovered(), "sample")
assert hasattr(Sensor, "sample") and not hasattr(Sensor(), "sample")
Exemplos
class Sensor:
@property
def sample(self):
raise AttributeError("offline")
print(hasattr(Sensor(), "sample"))
print(hasattr(Sensor, "sample"))
Resultado
False True
As outras exceções propagam-se.