Python: How to create object fields dynamically during init

Say you want to be able to create objects by passing them dictionaries with arbitrary numbers of pairs. Well this little trick, using setattr(), is going to come in handy for sure. This is all you have to do:

The only thing to remember is that the second argument in the setattr() call (“key” here) must be a string, as it represents the created field name.

Leave a Reply