getattr() Obter atributo de objeto
Última atualização: 2026-09-22
getattr() Obter atributo de objeto
getattr(obj, name[, default]) retorna o atributo name de obj; se não existir, retorna default (caso contrário, lança AttributeError).
| Categoria | Funções internas |
|---|---|
| Tipo | Função interna |
| Versão do Python | all |
📝 Sintaxe
getattr(object, name[, default])
⚙️ Parâmetros
| object Obrigatório | The object to read the attribute from. |
|---|---|
| name Obrigatório | The attribute name as a string. |
| default Opcional | Value returned if the attribute is missing.(Padrão:None) |
Retorno:The attribute value, or default if the attribute is missing.
💥 Exceções
AttributeError— Raised when the attribute is missing and no default is given.TypeError— Raised when name is not a string.
▶ Exemplo
Edite o código, clique em Executar e veja o resultado no painel de saída:
Saída:
10
default
🏷️ Funções internas relacionadas
💡 Casos relacionados
Mais estudos de caso em breve — aguarde.
❓ Perguntas frequentes
QQual é a diferença entre getattr(obj, 'x', 'default') e obj.x?
AQuando o atributo existe, os resultados são os mesmos; quando não existe, getattr retorna 'default', enquanto obj.x levanta AttributeError diretamente.
QEm que cenário sou obrigado a usar getattr?
AQuando o nome do atributo é calculado dinamicamente (vindo de variável, config ou concatenação de strings), getattr(obj, attr_name) não pode ser substituído pela sintaxe de ponto.
QComo getattr e hasattr trabalham juntos?
AVocê pode verificar com hasattr(obj, 'x') e depois usar getattr(obj, 'x'); de forma mais concisa, getattr(obj, 'x', None) resolve tudo em um passo.
QO que acontece se eu omitir default e o atributo não existir?
ALevanta AttributeError; se name não for uma string, levanta TypeError.