I'm trying to create an object with dynamic attributes:
props = {}
setattr(props, "aaaa", 'magic')
it says:
AttributeError: 'dict' object has no attribute 'aaaa'
Am I doing something wrong?
I'm trying to create an object with dynamic attributes:
props = {}
setattr(props, "aaaa", 'magic')
it says:
AttributeError: 'dict' object has no attribute 'aaaa'
Am I doing something wrong?
Am I doing something wrong?
Yes, you're trying to set attributes on an object of a built-in type. In Python, these behave a little differently from objects you create yourself.
So create a type yourself, and then an instance of it:
class myobject(object):
pass
props = myobject()
Now your setattr()
will work.
props = {}
props["aaaa"] = 'magic'
what you were trying to do was
props.aaaa = "magic"
Am I doing something wrong?
Well, you're doing two half things wrong:
Builtin classes (those defined in C) generally can't have attributes dynamically set.
There's no need to use setattr. If you have your own subclass of dict, you can just do props.aaaa = 'magic'
A python object can only have attributes added if it has a __dict__
. Looks like dict's don't.
See this answer for reference:Adding attributes to python objects
If its dictionaries you want to work with, this will help
props = {}
props.update({'aaaa':'magic'})