getattr() Get attribute

Last updated: 2026-09-22

getattr() Get attribute

getattr(obj, name[, default]) returns obj.name; returns default if missing (else raises AttributeError).

CategoryBuilt-in Functions
KindBuilt-in Function
Python Versionall

📝 Syntax

getattr(object, name[, default])

⚙️ Parameters

object RequiredThe object to read the attribute from.
name RequiredThe attribute name as a string.
default OptionalValue returned if the attribute is missing.(Default:None)

Returns:The attribute value, or default if the attribute is missing.

💥 Raises

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

10
default
More case studies coming soon — check back later.

❓ FAQ

QWhat is the difference between getattr(obj, 'x', 'default') and obj.x?
AWhen the attribute exists, the results are the same; when it does not, getattr returns 'default' while obj.x raises an AttributeError directly.
QIn what scenarios must I use getattr?
AWhen the attribute name is computed dynamically (from a variable, config, or string concatenation), getattr(obj, attr_name) cannot be replaced by dot syntax.
QHow do getattr and hasattr work together?
AYou can check with hasattr(obj, 'x') and then get with getattr(obj, 'x'); more concisely, getattr(obj, 'x', None) does it in one step.
QWhat happens if I omit default and the attribute does not exist?
AIt raises an AttributeError; if name is not a string it raises a TypeError.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏