Categories
Python Answers

How to programmatically set an attribute with Python?

Spread the love

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 can use the setattr function.

For instance, we write:

class C:
    foo = 1


c = C()
setattr(c, 'bar', 2)

print(c.bar)

We have the C class with the foo attribute.

Then we create an instance of C and assign it to c.

Next, we add the bar attribute to c with setattr(c, 'bar', 2).

Therefore, c.bar is now 2.

Conclusion

To programmatically set an attribute with Python, we can use the setattr function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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