What is the getattr() function in Python?
Overview
The getattr() function in used to obtain the value of an object’s attribute using the attribute’s name. The method returns a default value if the specified attribute is not the object’s attribute. If no default value is specified, then the method throws an exception.
Syntax
getattr(object, name[, default])
Parameters
object: The object whose attribute’s value has to be retrieved.name: The name of the attribute.default: The default value to return in case the attribute is not the object’s attribute.
Return value
The method returns the attribute value of the object. Otherwise, it returns the default value if specified.
Example
class Student:name = "sam"age = 12def getattr_without_default_value():student = Student()print("getattr() function without default values")print("student's name - ", getattr(student, "name"))print("student's age - ", getattr(student, "age"))try:print("student's grade - ", getattr(student, "grade"))except AttributeError as ex:print("Exception:", ex)def getattr_with_default_value():student = Student()print("getattr() function with default values")print("student's name - ", getattr(student, "name"))print("student's age - ", getattr(student, "age"))print("student's grade - ", getattr(student, "grade", "Not Found"))getattr_without_default_value()print("--" * 8)getattr_with_default_value()
Explanation
-
Lines 1–3: The
Studentclass is defined with attributesnameandage. -
Lines 6–14: We define a method called
getattr_without_default_valuewhere we define an instance of theStudentclass and try to obtain the attribute values using thegetattr()method without using any default values. For unknown attributes, an exception is thrown (see lines 11–14). -
Lines 17–22: We define a method called
getattr_with_default_valuewhere we define an instance of theStudentclass and try to obtain the attribute values using thegetattr()method with default values. For unknown attributes, the default value is returned.