Methods and Functions

Python getattr()

We use the Python setattr() function to assign a value to an object’s attribute. There might arise a situation where we might want to fetch the values assigned to the attributes. To provide this functionality, Python getattr() built-in function is used. Let us understand more about the Python getattr() function, its syntax, and its various examples in this article.

Definition

  • Python getattr() is a built-in function that is used to return the value of an attribute of a specific object/instance.
  • The Python getattr() function is used to obtain an object’s attribute value and also provides the option of executing the default value if the attribute is not available.

Python getattr()

Basically, Python’s getattr() built-in function is used to retrieve the value of the object’s attribute with the name string. If this specified attribute does not exist, then the value specified as an optional third default argument is returned. This happens only if the default_value is specified as a 3rd parameter. If neither of these exists, an AttributeError is thrown. The getattr() function accepts 2 or 3 values as its parameter.

  • Syntax 

                    

getattr(object, name, default_value)

  • getattr() Parameters 

object = instance of the function whose attribute is to be set

name = variable name/attribute name

default_value = When an attribute cannot be found, a value is to be returned. It is an Optional value.

Note – When we specify the attribute name parameter to fetch a value in the getattr() function, note that we must always enclose it with quotes or apostrophes i.e. “ ” or ‘ ’. This attribute name parameter should be passed as a string value.

  • Return value from getattr() 

Python getattr() returns one of the following –

  • Returns value of the specified attribute of an object
  • Returns default value, if the attribute is not found
  • If the named attribute is not found and the default is not defined, an AttributeError exception is thrown.

getattr() equivalent

Python getattr() also has an alternative. You must have seen this as it is the most commonly used method.

                    

object.attribute

So why use the getattr() function?

There are two basic reasons for this:

  • If the attribute does not exist, getattr() returns a default value, whereas the dot syntax returns an error.
  • getattr() allows you to access an attribute dynamically by using a string instead of its name. You might get the string as a user input, in which case you can’t utilize the dot syntax object. attribute because an attribute is a string rather than a name.

Example 1: How does getattr() work in Python?

In the following example, we have implemented a class ‘Employee’ with attributes ‘name’, ‘salary’, and ‘designation’. We have then created an object ‘e’ and then we have fetched the value of salary from object ‘e’ using the Python getattr() function.

Example

                    

# Python program to illustrate getattr() function
class Employee:
    name = 'David'
    salary = 55000
    designation = 'Marketing Head'

e = Employee()  

print('Salary of David is:', getattr(e, 'salary'))
#This is equivalent to
print('Salary of David is:', e.salary)

Output

                    

Salary of David is: 55000
Salary of David is: 55000

Example 2: getattr() when named attribute is not found

Example

                    

# Python program to illustrate getattr() function
class Employee:
    name = 'David'
    salary = 55000
    designation = 'Marketing Head'

e = Employee()  

print('Age of David:', getattr(e, 'age', 56))
print('')
print('Age of David:', getattr(e, 'age'))

Output

                    

Age of David: 56

Traceback (most recent call last):
File "", line 10, in 
AttributeError: 'Employee' object has no attribute 'age'

In the above program, the attribute ‘age’ is missing from the class ‘Employee’. For the first print statement, getattr() creates a new attribute for the object only if the default value is specified in the argument. In the second print statement, the ‘age’ attribute is missing from the class as well as the default value. Hence, the Python interpreter displays an ArrtibuteError.

Frequently Asked Questions

Q1. What is getattr() used for in Python?

We use the Python setattr() function to assign a value to an object’s attribute. There might arise a situation where we might want to fetch the values assigned to the attributes. To provide this functionality, Python getattr() built-in function is used. Basically, Python’s getattr() built-in function is used to retrieve the value of the object’s attribute with the name string.

Q2. What is __getattr__ in Python?

Python calls the __getattr__ method whenever the requested attribute hasn’t already been defined. It means that. When an attribute lookup does not find the attribute in the typical places, this method is called. This function should either return the (computed) attribute value or throw an AttributeError exception if it fails.

It should be noted that if the attribute is discovered using the standard approach, __getattr__() is not invoked.

Q3. What is getattr() and setattr() in Python?

Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.

Syntax

                    

setattr(object, name, value)

where,

value = value to be set for the attribute

Example

                    

# Python program to illustrate setattr() function
class Details:
    name = 'Sam'
    age = 24

# Create an object of the class
d = Details()

print('Name before modification:', d.name)
print('Age before modification:', d.age)

setattr(d, 'name', 'Timmy')
setattr(d, 'age', 27)

print('Name after modification:', d.name)
print('Age after modification:', d.age)

Output

                    

Name before modification: Sam
Age before modification: 24

Name after modification: Timmy
Age after modification: 27

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.