0

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?

user3175226
  • 3,579
  • 7
  • 28
  • 47

5 Answers5

3

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.

kindall
  • 178,883
  • 35
  • 278
  • 309
2
props = {}
props["aaaa"] =  'magic'

what you were trying to do was

 props.aaaa = "magic"
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • 2
    In this case you are not setting a dynamic attribute to an object. Your are setting a value to a key in a Python Dictionary. – user3557327 Jul 24 '14 at 19:30
1

Am I doing something wrong?

Well, you're doing two half things wrong:

  1. Builtin classes (those defined in C) generally can't have attributes dynamically set.

  2. There's no need to use setattr. If you have your own subclass of dict, you can just do props.aaaa = 'magic'

Marcin
  • 48,559
  • 18
  • 128
  • 201
0

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

Community
  • 1
  • 1
0

If its dictionaries you want to work with, this will help

props = {}
props.update({'aaaa':'magic'})
shshank
  • 2,571
  • 1
  • 18
  • 27