Python 3 reference · Built-in Functions
Python getattr() Function
Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.
Python 3 Since 3.0
Syntax
getattr(object, name)
getattr(object, name, default)
Parameters
| Parameter | Description |
|---|---|
object |
Any object. |
name |
The attribute name as a string. |
default optional |
Returned if the attribute doesn't exist. |
Return value
The attribute's value, or default.
Examples
class User:
name = "Ada"
u = User()
print(getattr(u, "name"))
print(getattr(u, "email", "no email"))
Output
Ada no email
class Calculator:
def add(self, a, b): return a + b
def mul(self, a, b): return a * b
calc = Calculator()
for op in ["add", "mul"]:
print(op, getattr(calc, op)(6, 7))
Output
add 13 mul 42
Good to know
getattr(obj, "x") is the same as obj.x; it is only useful when the name is in a variable. Without a
default, a missing attribute raises AttributeError.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
setattr()· Set an attribute on an object by name, given as a string. setattr(obj, 'x', 5) is the same as obj.x = 5.hasattr()· Return True if an object has an attribute with the given name. It works by calling getattr() and catching AttributeError.delattr()· Delete a named attribute from an object. delattr(obj, 'name') does the same as del obj.name when the name is in a variable.vars()· Return the __dict__ of a module, class or object: its writable attributes as a dictionary. With no argument, like locals().- Python Classes and Objects · tutorial