Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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: