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.
getattr(object, name[, default])
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.The method returns the attribute value of the object. Otherwise, it returns the default value if specified.
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()
Lines 1–3: The Student
class is defined with attributes name
and age
.
Lines 6–14: We define a method called getattr_without_default_value
where we define an instance of the Student
class and try to obtain the attribute values using the getattr()
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_value
where we define an instance of the Student
class and try to obtain the attribute values using the getattr()
method with default values. For unknown attributes, the default value is returned.