Python's built-in setattr
function can dynamically set attributes given an object, a string representing an attribute name, and a value to assign.
Table of contents
Need to dynamically set an attribute?
We'd like to make a class that works like this:
>>> row=Row(id=4,name="duck",action="quack",color="purple")>>> row.id4>>> row.name'duck'
>>> row=Row(id=4,name="duck",action="quack",color="purple")>>> row.id4>>> row.name'duck'
Our Row
class is supposed to accept any number of keyword arguments and assign each of them to an attribute on a new Row
object.
We can use Python's **
operator to capture arbitrary keyword arguments into a dictionary:
classRow:def__init__(self,**attributes):forattribute,valueinattributes.items():...# What should we do now?
classRow:def__init__(self,**attributes):forattribute,valueinattributes.items():...# What should we do now?
But we need some way to store each item on our Row
object as a new attribute.
Normally attribute assignments use an =
sign with the .
notation:
>>> row.color="purple"
>>> row.color="purple"
But we can't use the .
notation because our attribute names are stored in strings.
For example the variable attribute
might contain the string "color"
(representing the color
attribute we're meant to assign to):
>>> attribute="color">>> value="purple"
>>> attribute="color">>> value="purple"
And if we try using Python's usual attribute assignment notation:
>>> row.attribute=value
>>> row.attribute=value
We'll end up with an attribute called attribute
instead of an attribute called color
:
>>> row.attribute'purple'
>>> row.attribute'purple'
We need some way to dynamically assign an attribute!
Python's built-in setattr
function to the rescue
Python's setattr
function accepts an …