Python getattr() Function
Gets the value of an attribute of an object. While normally one just gets the value to
an attribute (for example, name = person.name
), in meta-programming, it can
is often useful to be able to get an attribute by its name.
Syntax
Python
Copy Code
getattr(object, name)
Parameters
Parameter | Description |
---|---|
object |
Required. The object from which to get the value |
name |
Required. The name of the attribute whose value is to be returned. |
Example
Python
Copy Code
class Person: def __init__(self): self.name = 'Andy' person = Person() name = getattr(person, 'name') print(name)
Output
Andy
Notes
If a default value is not specified, Python will throw an AttributeError
exception
if the attribute is not defined in the class. By providing a default
value, Python returns the default value if the attribute is not defined in the
class.
Example
Python
Copy Code
class Person: def __init__(self): self.name = 'Andy' person = Person() firstName = getattr(person, 'firstName', 'Person has no firstName!') print(firstName)Output:
Person has no firstName!