Built-in Functions and Types
getattr()
Read an attribute whose name is supplied at runtime. Ordinary attribute lookup applies, so descriptors and custom lookup hooks can execute code. A supplied default replaces AttributeError from lookup; other exceptions propagate. Without a default, a missing attribute raises AttributeError. A string name need not be a valid Python identifier; name mangling is not applied automatically.
Formal Syntax & Structure
python syntaxpython
getattr(object, name, /)getattr(object, name, default, /)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| object | object | Target of lookup. |
| name | str | Attribute name. |
| default | object | Fallback if lookup raises AttributeError. |
Return Value
object
Attribute value or supplied fallback.
Working Example
Example Snippetpython
class Product: price = 12
item = Product()print(getattr(item, "price"))print(getattr(item, "discount", 0))