Menu Close

How to programmatically set an attribute with Python?

Sometimes, we want to programmatically set an attribute with Python.

In this article, we’ll look at how to programmatically set an attribute with Python.

How to programmatically set an attribute with Python?

To programmatically set an attribute with Python, we call setattr.

For instance, we write

setattr(x, attr, 'magic')

to call the setattr function to set the x‘s attr attribute to 'magic' where attr is a string with the attribute name.

Conclusion

To programmatically set an attribute with Python, we call setattr.

Posted in Python, Python Answers