Python getattr() With Examples

In our previous tutorial we learned about python system command. In this tutorial we will be discussing about Python getattr() function.

Python getattr() function

Python getattr() function is used to get the value of an object’s attribute and if no attribute of that object is found, default value is returned.

Basically, returning the default value is the main reason why you may need to use Python getattr() function. So, before starting the tutorial, lets see the basic syntax of Python’s getattr() function.

Python getattr() example

In this section, we will learn how to access attribute values of an object using getattr() function. Suppose, we are writing a class named Student. The basic attributes of Student class are student_id and student_name. Now we will create an object of the class Student and access it’s attribute.

So, the output will be like this


Python getattr() default value

In this section, we will use the python getattr() default value option. If you want to access any attribute that doesn’t belong to the object, then you can use the getattr() default value option.

For example, if the student_cgpa attribute is not present for the student, then will show a default value.

In the following example we will see example of default value. We will also learn what happens if the attribute is not present and we are not using the default value option.

So, after running the code you will get output like this

Notice that AttributeError is raised when the default value is not provided while calling getattr() function.

Reason for using Python getattr() function

The main reason to use python getattr() is that we can get the value by using the name of the attribute as String. So you can manually input the attribute name in your program from console.

Again, if an attribute is not found you can set some default value, which enables us to complete some of our incomplete data.

Also if your Student class is work in progress, then we can use getattr() function to complete other code. Once Student class has this attribute, it will automatically pick it up and not use the default value.

So, that’s all about python getattr() function. If you have any query about this, please use the comment box below.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: