Python getattr() method

In this tutorial, we are going to learn about getattr() method in Python. We use this method to find out the value of a particular attribute of an object. The syntax and use of getattr() method in Python have been discussed here.

Python getattr() method: syntax and uses

The syntax for getattr() is as follows:

getattr(object_name, attribute_name[, default_value])

This method returns:

  • value of the given attribute.
  • default value if the attribute is not found.
  • AttributeError if the attribute is not found and the default value is not provided.

Let’s understand this with an example program.

class Name:
    fname = "Ranjeet"
    lname = "Verma"
    
name = Name()

print("First name using getattr(): ", getattr(name,"fname"))
print("First name without using getattr():", name.fname)

print("\nLast name using getattr(): ", getattr(name,"lname"))
print("Last name without using getattr(): ", name.lname)

Output:

First name using getattr(): Ranjeet
First name without using getattr(): Ranjeet

Last name using getattr(): Verma
Last name without using getattr(): Verma

As you can see in the above program, We have created a class Name. We have defined attributes fname and lname for this class. Then we create an object of this class. Now, in the next line, we have used getattr() to get the value of fname attribute. And in the same way, we can get the value of lname object as done in the example above.

Default value for an attribute in getattr() method

We can also give a default value for an attribute in case that attribute does not exist for that object. See the example.

class Name:
    fname = "Ranjeet"
    lname = "Verma"
    
name = Name()

print("Full name: ", getattr(name, "fullname", "Ranjeet Verma"))

Output:

Full name: Ranjeet Verma

As you can notice that we have not provided any attribute with name fullname for the class Name. But we have used getattr() method to get the value of fullname attribute for name object. Since there is no attribute as fullname, the default value is printed for it, which has been given as the third parameter here.

Note: If the attribute in the getattr() method has already some value, then that value will be returned, not the default value.

Thank you.

Also, read: Python setattr() Function

Leave a Reply

Your email address will not be published. Required fields are marked *