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 Intro to Inheritance

Why set anything with self.x, and just use setattr()?

It seems weird to me to layout specific attributes, then put a generic way to catch random attributes. It seems like it would be a lot less code to just put setattr() at the beginning and forget about anything specific.

Also, in regards to this videos example, would that be a standard practice? Would I add that to all my classes if I were a programmer?

Thanks

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Looping over **kwargs works if you have no concerns over managing parameters. Using this method has its drawbacks

  • **kwargs would allow any attribute or method to be overwritten. Using a "whitelist" adds some protection.
  • It doesn't handle misspelled arguments.

Using self.x is shorthand. Behind the scenes, setattr(self, 'x', 123) is equivalent to self.x = 123.

In many situations, it's better to be explicit and list the arguments you are expecting, or check each kwarg against a whitelist.