Python getattr() Function

The getattr() function in Python is used to get the value of a specified attribute in a specified object. For example:

class CodesCracker:
    Name = "Charlotte"
    City = "Edmonton"
    Course = "Data Science"
    University = "University of Toronto"

print(getattr(CodesCracker, "Course"))

The output will be:

Data Science

Python getattr() Function Syntax

The syntax of getattr() function in Python, is:

getattr(obj, attr, def)

where:

Python getattr() Function Example

The example of getattr() function in Python, is given below. This program allows user to define the attribute. The function getattr() is used to get the value of given attribute. I've used the default parameter (third parameter) to return the default value, if the attribute does not exist in the specified object:

class CodesCracker:
    Name = "Charlotte"
    City = "Edmonton"
    Course = "Data Science"
    University = "University of Toronto"

print("Enter the Attribute to Get the Value: ", end="")
attr = input()
val = getattr(CodesCracker, attr, "Not Found!")
print("\nThe value corresponding to given attribute =", val)

The snapshot given below shows the sample run, with user input University as attribute:

python getattr function

Another sample run with user input as attribute say Address that does not exist in the specified object, is shown in the following snapshot:

python getattr function example

Without using try-except block, indirectly the exception gets handled using the getattr() using its default parameter, we can say. The value can also be used using the attribute of an object in this way:

print(CodesCracker.Name)

prints the value of Name attribute of CodesCracker object.

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!