Getattr () function in python

Python Methods and Functions

The getattr () function in Python helps you get an attribute of an object. This is very similar to the setattr () function , but does not change the object.

 Getattr




Basic getattr () syntax

The syntax for the getattr () function is as follows:



 value = getattr (object, attribute_name [, defau lt_value]) 

Here we pass the object to getattr () . It tries to get the attribute_name (which should be a string) of this object. If the attribute exists, it will give us the corresponding value .

This is equivalent to the syntax:

 value = object.attribute_name 

Otherwise there are two possible cases:

  • If a default ( default_value ) is specified, it will just use it and will return the value of that default.
  • Otherwise, it will simply throw a AttributeError Exception because our attribute was not found.

Task getattr () ¬ only get the value of an attribute, but also check for its existence!




Examples

Let's first look at a simple example where you have a Student class with name attributes and roll_num . We get them with getattr () .

 class Student (): def __init __ (self, name, roll_no ): self.name = name self.roll_no = roll_no student = Student ('Amit', 8) print (f" Name: {getattr (student, 'name')}") print (f "Roll No: {getattr ( student, 'roll_no')}") 

Exit

 Name: Amit Roll No: 8 

Indeed, we have set the correct attributes and are returning them with getattr () !



In this case, since both attributes were present, there were no errors. However, let's try to get an attribute that we haven't put in the class; for example & age .

 class Student (): def __init __ (self, name, roll_no): self.name = name self.roll_no = roll_no student = Student ('Amit', 8) print (f" Name: {getattr (student, 'name')}") print (f "Roll No: {getattr (student,' roll_no')} ") # Will raise' AttributeError' Exception since the attribute 'age' is not defined for our instance print (f" Age: {getattr (student, 'age')}") 

Exit

 Name: Amit Roll No: 8 Traceback (most recent call last): File "getattr_example.py", line 12, in & lt; module & gt; print (f "Age: {getattr (student,' age')} ") AttributeError:' Student' object has no attribute 'age' 

Here we tried to get an attribute that was not defined. Since there were no default parameters, Python threw an exception directly.

If we want to set the default parameter to '100' , then in this case, although we are trying to get age since it isn't there, it will return 100 instead.

Let's check it out.

 class Student (): def __init __ (self, name, roll_no): self.name = name self.roll_no = roll_no student = Student ('Amit', 8) print (f" Name: {getattr ( student, 'name')}") print (f "Roll No: {getattr (student,' roll_no')} ") # Will not raise AttributeError, since a default value is provided print (f" Age: {getattr (student , 'age', 100)}") 

Exit

 Name: Amit Roll No: 8 Age: 100 



Why use getattr ()?

Since we mentioned earlier that this function is equivalent to object.attribute_name , what is the point of this function and?

While the above statement using notation is correct, it is only valid if the attribute name is actually defined at the time of the call.

So, if your classes are such that the structure object changes from time to time, you can use getattr () to check if the object is in some particular state.

This also gives us a nice way to handle exceptions easily, and also provide fallback defaults. If something went wrong, we could either catch the AttributeError exception or check the default.







Get Solution for free from DataCamp guru