Python setattr()

Filed Under: Python

Python setattr() function allows us to set an object attribute value.

Python setattr()

Python setattr() function syntax is:


setattr(object, name, value)

This function is counterpart of python getattr() function.

The input arguments are object whose attribute will be set, name is the attribute name and value is the attribute value.

Let’s look at a simple example of setattr() function.


class Data:
    pass


d = Data()

d.id = 10

print(d.id)

setattr(d, 'id', 20)
print(d.id)

Output:


10
20

So setattr() does the exact same thing as using dot operator with the object.

So where is the benefit of using setattr() function?

The setattr() function is useful in dynamic programming where the attribute name is not static. In that case, we can’t use the dot operator. For example, taking user input to set an object attribute and its value.

Python setattr() example with user input


d = Data()
attr_name = input('Enter the attribute name:\n')
attr_value = input('Enter the attribute value:\n')

setattr(d, attr_name, attr_value)

print('Data attribute =', attr_name, 'and its value =', getattr(d, attr_name))

Output:


Enter the attribute name:
name
Enter the attribute value:
Pankaj
Data attribute = name and its value = Pankaj

python setattr example

Python setattr() exception

We can create a read-only attribute in the object using property function or property decorator.

In that case, if we try to set the attribute value using setattr() function, we will get AttributeError: can't set attribute exception.


class Person:

    def __init__(self):
        self._name = None

    def get_name(self):
        print('get_name called')
        return self._name

    # for read-only attribute
    name = property(get_name, None)


p = Person()

setattr(p, 'name', 'Pankaj')

Output:


Traceback (most recent call last):
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_setattr_example.py", line 39, in <module>
    setattr(p, 'name', 'Pankaj')
AttributeError: can't set attribute
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages