Python Glossary Русский

all Python 3Built-in functionsterm

getattr

OOP

Gets an attribute of an object by its name given as a string. The third argument is the default value used when the attribute does not exist (otherwise AttributeError).

Syntax

getattr(object, name[, default])

The default is evaluated eagerly, before the lookup even happens — if computing it is expensive or has side effects, check with hasattr instead. The subtler trap: the default kicks in on any AttributeError, including one raised inside a property's own code, so a real bug in that property silently turns into "attribute missing".

Examples

class A:
    x = 42
a = A()
print(getattr(a,'x'))  # → 42
print(getattr(a,'y',None))  # → None
getattr([1,2,3],'append')(4)  # → [1,2,3,4]
print(getattr('hello','upper')())  # → HELLO
name = 'x'; print(getattr(a, name))  # → 42

See also

Open in the full glossarydocs.python.orgReport an inaccuracy