Home / Python / Reference / Built-in functions

Python getattr() function

Get an attribute by its name as a string.

Syntax

getattr(obj, name, default)

Useful when the attribute name is only known while the program runs. With a default, a missing attribute gives the default instead of an error.

Parameters

objthe object
namethe attribute name, as a string
defaultreturned if it does not exist

Return value

the attribute value

Example

Code

class Dog:
    def __init__(self, name):
        self.name = name
d = Dog("Rex")
print(getattr(d, "name"))
print(getattr(d, "age", "unknown"))
print(getattr("text", "upper")())

Output

Rex
unknown
TEXT

Related

Learn it step by step in the free lesson Classes & Objects, with exercises that check your answers.