Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Instant Objects Method Arguments

Instead of using setattr() to set attributes from **kwargs, is there a reason the following code doesn't work:

Is there a reason the following code doesn't work:

class Thief:

  def __init__(self, name, **kwargs):
    self.name = name
    for attribute, value in kwargs.items():
      self.attribute = value

1 Answer

I may be wrong, as I am not an expert in python, but in javascript, using dot notation makes it literal, while bracket notation makes it dynamic.

I suspect the same to apply for python in this case.

So by saying self.attribute = value you are literally setting the key value pair as "attribute" = value. You want of course attribute to be dynamic,

Maybe self[attribute] may work.

Edit:

after some testing it is indeed setting the Thief.attribute to value, however bracket notation seems to not work in python the same way as it does in javascript, so my suggested solution will not work.