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
| obj | the object |
| name | the attribute name, as a string |
| default | returned 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.