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 (retired) Inheritance Instance Methods

Smith Thapa
Smith Thapa
7,023 Points

Can not understand the loop given below

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

Please explain in details.

2 Answers

Steven Parker
Steven Parker
231,271 Points

I think you meant items() (plural). The items method converts a dictionary (kwargs) into a list of key/value tuples.

So then "for key,value in kwargs.items()" is a loop that will operate on each key and value pair.

Finally, "setattr(self,key,value)" will establish an attribute with the same name as key and the value of value.

The entire loop is just a handy way to establish some attributes based on what was in a dictionary.

Does that make it clearer?

Smith Thapa
Smith Thapa
7,023 Points

I understood the function of items() but can you elaborate the workings of setattr() function ?

Zach Hudson
Zach Hudson
7,702 Points

Hi Smith Thapa, check out this question in the Treehouse Community: What does setattr() actually do?.

I think the above link/question will help bring clarity to your question, but at a very basic level setattr() just sets values to attributes.