Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

getattr()

Lê o atributo indicado pela cadeia com as regras normais, incluindo descritores.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

getattr(object, name[, default])

Lê o atributo indicado pela cadeia com as regras normais, incluindo descritores.

O valor predefinido só substitui o AttributeError final. Se a função de leitura gerar essa exceção, __getattr__ ainda pode fornecer um valor. Box.value existe com valor None e prevalece sobre 7. Se faltar o atributo devolve-se o 7 fornecido ou gera-se AttributeError.

Outra exceção da leitura, como ValueError, propaga-se.

class Box:
    value = None
    @property
    def broken(self): raise ValueError("bad")
class Recovered(Box):
    @property
    def missing(self): raise AttributeError
    def __getattr__(self, name): return 11
assert getattr(Recovered(), "missing", 7) == 11
b = Box()
assert getattr(b, "value", 7) is None and getattr(b, "absent", 7) == 7
try:
    getattr(b, "broken", 7)
except ValueError:
    pass
else:
    raise AssertionError

Exemplos

class Box:
    value = None

print(getattr(Box, "value", 7))
print(getattr(Box, "missing", 7))

Resultado

None
7

Outra exceção da leitura, como ValueError, propaga-se.

Fontes