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

Antoni Majewski
Antoni Majewski
3,128 Points

len() 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
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Good 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!!!

Chris, 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
Chris Freeman
Treehouse Moderator 68,441 Points

Izabella 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
Chris Freeman
Treehouse Moderator 68,441 Points

For 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.

Thank you Chris!