Categories
Python Answers

How to access class property from string with Python?

Spread the love

Sometimes, we want to access class property from string with Python.

In this article, we’ll look at how to access class property from string with Python.

How to access class property from string with Python?

To access class property from string with Python, we can use the setattr method to set attribute values and getattr to get attribute values.

For instance, we write

class C:
    pass

o = C()

setattr(o, "foo", "bar")
v = getattr(o, "foo")

to create class C.

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

Next, we call setattr to add the o.foo attribute and set it to 'bar'.

And then we call getattr to get the value of the o.foo property.

Conclusion

To access class property from string with Python, we can use the setattr method to set attribute values and getattr to get attribute values.

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 *