Menu Close

Python getattr() Function

In this built-in function tutorial, we are going to learn all about Python getattr function to return the value of a specified attribute of the specified object. To understand this python, you should have basic knowledge of the Python class and object.

In the previous tutorial, we have seen all about the python-format function to format the specified value with the specified format.

Python getattr() function

Python getattr function is a Python built-in function that is used to get the value of a specified attribute from the specified object. Python getattr method gives another facility to assign a default value if the specified attribute does not exist.

Syntax

The syntax of getattr function in python is:-

getattr(object, attribute, value)

Parameter

getattr function in python support three parameters.

  • object:- Required, An object.
  • attribute:- The name of the attribute you want to value from.
  • value:- Value to be returned, If the specified attribute does not exist.

Return Value

The return value of python getattr method is, value of attribute.

Python getattr example

To understand python getattr function, we have created a simple class named Student.

Example:

#Create class 
class Student:
    name = 'Vishvajit'
    roll = 100
    course = 'BCA'
    occupation = 'Programmer'
    

#Use getattr function to get the value of name attribute.
result = getattr(Student, 'name')
print(result)

Output will be:- Vishvajit

What happens, If the specified attribute does not exist, let see.

Example:

#Create class 
class Student:
    name = 'Vishvajit'
    roll = 100
    course = 'BCA'
    occupation = 'Programmer'
    

#Use getattr function to get the value of the address attribute that does not exist.
result = getattr(Student, 'address')
print(result)

If you will execute above program, you will get an error like below.

Traceback (most recent call last):
  File "C:\Users\Vishvajit\Desktop\PF Article\Python Basic part1\test.py", line 10, in <module>
    result = getattr(Student, 'address')
AttributeError: type object 'Student' has no attribute 'address'

To solve above problem, you can use python getattr function’s third parameter that is default value.

Example:

#Create class 
class Student:
    name = 'Vishvajit'
    roll = 100
    course = 'BCA'
    occupation = 'Programmer'
    

#Use getattr function to get the value of address attribute.
result = getattr(Student, 'address', 'Noida')
print(result)

Output will be:- Noida

Conclusion

So In this article, you have learned python getattr function to get the value of specified attribute from specified object along with various example. If this article really helpful for your, please share with your friends who want to learn this type of python programs.

Other Python built-in functions


For more information:- Click Here

Previous Article
Next Article

Related Posts

Leave a Reply