getattr() Built-in Function

Python – getattr()

Python getattr() built-in function gets the value assigned for an attribute of an object.

In this tutorial, we will learn the syntax and usage of getattr() built-in function with examples.

Syntax

The syntax of getattr() function is

getattr(object, attribute)
getattr(object, attribute, default)

where

ParameterMandatory/
Optional
Description
objectMandatoryA Python object.
attributeMandatoryattribute is a string value.
defaultOptionalAny arbitrary value.

If given attribute does not exist for the object, then AttributeError is raised. But, if default value is given, then the default value is returned.

Examples

1. Get attribute of a class object

In the following program, we define a class named Student. This class has three attributes: name, age, and country.

We create a new object of the class type Student with some some values, and then read the attribute values of this object using getattr() function.

Python Program

class Student:
    def __init__(self, name, age, country):
        self.name = name
        self.age = age
        self.country = country

student1 = Student('Mike', 12, 'Canada')

name = getattr(student1, 'name')
print(name)
Run Code Copy

Output

Mike
  • Python setattr() This built-in function sets the value of an attribute of an object.
  • Python hasattr() This built-in function checks if the object has the specified attribute.
  • Python delattr() This built-in function deletes the attribute from an object.

Summary

In this Built-in Functions tutorial, we learned the syntax of the setattr() built-in function, and how to use this function to read the value of an attribute of an object.

Related Tutorials

Code copied to clipboard successfully 👍