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 trialAntoni Majewski
3,128 Pointslen() vs. __len__
Hello,
I don't understand when I should define __len__
here, and not just len() - what's the difference?
Thanks~!
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsGood question. The function len()
is a built-in function in python and should not be user defined. The proper way to get the length of an object is to call the built-in function with the object as the argument: len(obj)
The built-in len()
will call the object’s __len__
method. So it is the __len__
method that should be defined.
Post back if you need more help. Good luck!!!
Izabella Exeoulitze
Courses Plus Student 1,665 PointsThank you Chris!
Izabella Exeoulitze
Courses Plus Student 1,665 PointsIzabella Exeoulitze
Courses Plus Student 1,665 PointsChris, thanks for the answer. I have a clarification question for you: are you saying that we cant modify/define len() but everything that has dunder is 'modifiable'? Much appreciate all your help. Isabella
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsIzabella Exeoulitze, yes, the dunder methods are how an class responds to a call by the built in functions. Those can be modified and overridden as needed. The built in functions should not be modified.
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsFor those that asked, if you are defining a class that does not inherit from a built-in type, will not inherit a
__len__
method. So if you wish to use len() on this class the__len__
method will need to be defined.