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

I still don't understand the python build in function "setattr". Could some1 explain to me?

If you could, plz explain how this setattr function works Moreover, how does this code work too? if you could, plz explain it with an example.

for key, value in kwargs.items():
            setattr(self, key, value)

2 Answers

# Both these lines are the same. They will do the same thing. I think setattr looks a little nicer.

setattr(jacinator, "languages", ["English", "French"])

jacinator.languages = ["English", "French"]

how did mr Love explain these in video?

Which video? I've been writing Python for longer than I've been on Treehouse, so I only half paid attention to some of the basics videos.

The video is in the python object video. Thx for help anyway.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

setattr sets an attribute on an object. Let's pretend we have an object that's of a Book class. We'll call it novel.

novel = Book()

Now, if I want to explicitly set novel's title attribute, I can do novel.title = "The Wizard of Oz". And that works great so long as I know the name of the attribute I want to set in my code. I have to be able to type out the attribute name.

But if I don't know the name of the attribute, I can't do it that way. I can't do novel.$attribute = "The Wizard of Oz" where attribute would come from some outside source. Python doesn't allow that. Python does, however, have this setattr function. Using setattr, I can set an attribute on an object whether I know the attribute's name or not.

setattr(novel, "title", "The Wizard of Oz") or

attribute = "title"
setattr(novel, attribute, "The Wizard of Oz")

All of these examples produce the exact same object: a Book instance named novel that has a title attribute with the value of "The Wizard of Oz".

Thx master Love explains this to do. i think i understant little bit of it.