Python Built-in Function getattr():

The getattr() is an inbuilt function in Python that is used to get the value of the named attribute of the object. However, if the named attribute does not exist, it returns the default value if provided; otherwise, it raises an AttributeError exception.

Signature

The signature for the getattr() function is as shown below.

o=getattr(object, name, default)

Parameters and return type

  • Here, an object represents one whose attributes need to be processed. The name refers to the attribute of the object. Whereas it prints value given in default if in case the attribute is not present.
  • However, this function returns object value if the value is available, the default value in case the attribute is not present. It returns AttributeError in case an attribute is not present and the default value is not specified.

Python Built-in Function getattr Examples:

Example 1: For example, let us take a class student having attribute name and age initialized with the values. Now, we will use this function to get the value of the attribute from the class without using an instance of the class.

#Defining a class
class student:
name = 'Ram'
age = 25
#getting attribute and printing
r = getattr(student, 'name')
print(r)

Output

Ram

Example 2: In this example, we will take the same student class and try to access the attribute that is not present in the class. But, here we will specify the name and the default value of the attribute. So that if a given attribute is not present, this method prints the default name and value without raising an exception.

#Defining a class
class student:
name = 'Ram'
age = 25
#getting attribute and printing
r = getattr(student, 'name')
print(r)
r = getattr(student, 'location','Mumbai')
print(r)

Output

Ram
Mumbai

Example 3: In this example, We will take student class once again and will not pass the default value for an attribute. So if an attribute is not present in the class, this statement will raise an AttributeError exception.

#Defining a class
class student:
name = 'Ram'
age = 25
#getting attribute and printing
r = getattr(student, 'location')
print(r)

Output

Traceback (most recent call last):
File "main.py", line 5, in 
r = getattr(student, 'location')
AttributeError: type object 'student' has no attribute 'location'

Conclusion

The getattr() function returns the value of an attribute. However, if in absence of an attribute, it returns the default value if available, or raises an exception otherwise.

References

Happy Learning 🙂

Leave A Comment