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 trialBenyamin Kohanchi
Courses Plus Student 2,342 PointsThe difference between dunder len and len()
Kinda confused between dunder len and len(), is dunder len object-oriented while len() is not?
Thanks in advance 😁
1 Answer
Josh Keenan
20,315 PointsWell __len__
is len()
. When you call the function, it uses that objects __len__
method to evaluate what it should do with this type of object. It was thought that it would be easier using len(a)
instead of a.len()
, so they got it to work like this. Sorry I don't know as much about this as I should, but I hope this helps!
Benyamin Kohanchi
Courses Plus Student 2,342 PointsBenyamin Kohanchi
Courses Plus Student 2,342 PointsGreat, thanks Josh!
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsGreat answer. Most of the dunder methods are defined to be called by a corresponding built-in function. If one really wanted to have
a.len()
functionality also work, alen
method could be added (though not recommended):So,
a.len()
calls thelen
method that, in turn, calls the built-in functionlen()
which would call the__len__
method. The__len__
method might be defined locally or inherited from a standard type. Caution: the linereturn self.len(self)
would cause a recursive stack overflow since the method calls itself. Good luck!!Benyamin Kohanchi
Courses Plus Student 2,342 PointsBenyamin Kohanchi
Courses Plus Student 2,342 PointsThanks for the example Chris, it helped!