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.


The syntax of getattr() function is

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


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.


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): = name
        self.age = age = country

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

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


  • 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.


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 👍