Dynamic setattr in Python
Level 4189 keystrokes
This uses setattr() to dynamically add attributes to an object from a dictionary.
Python code
# An empty class; attributes will be added at runtime1class DynamicObj:2 pass3 # Create an instance with no attributes yet4obj = DynamicObj()# Attribute names and values to set5data = {"name": "Alice", "age": 30, "city": "Tokyo"}6 # Loop over each key-value pair7for key, value in data.items(): # setattr(obj, key, value) is obj.<key> = value with the name as a string8 setattr(obj, key, value)9 # The new attributes work like normal ones: Alice 30 Tokyo10print(obj.name, obj.age, obj.city)Output
Alice 30 Tokyo
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
"× 10,× 7:× 5.× 4(× 4)× 4=× 2{× 1}× 1