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 Advanced Objects Emulating Built-ins

when to use dunder and when not to?

in case of defining "add" method he didn't use dunder, but for "contains" he used dunder. why is that?

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, E. T.! Your own custom classes/objects don't naturally have access to some things you're used to. For instance, imagine that you had a Student object that had attributes of name, major, grade point average etc. And let's say you made an instance of that object with new_student = Student(). What do you suppose would happen if you did len(new_student). What would you expect it to return? Well, that's entirely up to you, the developer. But you could have it return the length of their full name, or just their last name or anything you like. And you would do that by creating a __len__. The __len__ is what runs every time you do a len() of something :smiley:

As for the, __contains__ it is what is run every time you do a for something in other_thing. Specifically, it's that in word there that makes it look for a __contains__ on the object. I suggest taking a peek at this Python documentation about dunder contains

Hope this helps! :sparkles: