The getattr() function is one of Python's built-in functions used to retrieve the value of a specified attribute from an object.
Function Syntax
getattr(object, name[, default])
Parameters:
object: The object from which to retrieve the attribute.name: The name of the attribute to retrieve. This can also be a method name.default: Optional parameter specifying the default return value if the attribute doesn't exist.
When using getattr() to retrieve an attribute, if the attribute doesn't exist, it raises an AttributeError exception, unless the default parameter is provided as an alternative return value.
getattr() Function Examples
Here are some examples using the getattr() function:
class MyClass:
def __init__(self):
self.x = 123
def myprint(self, msg):
print(msg)
obj = MyClass()
# Get value of obj.x
val = getattr(obj, 'x')
print(val) # Output: 123
# Get obj.myprint method
val = getattr(obj, 'myprint')
# Call obj.myprint function
val("hello world")
# Get obj.myprint123, attribute doesn't exist, default value is print
val = getattr(obj, 'myprint123', print)
val("3.14159")
# Get value of obj.y, return default value 0 if it doesn't exist
val = getattr(obj, 'y', 0)
print(val) # Output: 0
# Get value of obj.y, attribute doesn't exist and no default defined
# Will trigger AttributeError
val = getattr(obj, 'y')