Why do we need a dunder method if list already has len()?

A question: Are these “re-defined” dunder methods for matching the input data types or is this a coincidence?

In the UserGroup example, we put in dunders like __iter__, __len__, __contains__ to users that are designed to make a list work and, the corresponding parameters in can_edit and can_delete are lists. So I am guessing that we know beforehand we were going to put lists in and thus we write these list dunders in. Is this correct? If this is correct, then I am puzzled again — isn’t the idea of redefining dunder methods making them do something different from what it originally does? And since it is a list itself, why do we need to define these operations again?

This is really a complicated part for me. Thanks in advance!

Remember that UserGroup isn’t a list, but that it contains a list. These dunder methods allow us to use len for example, directly on the class and it will return the length of the list that UserGroup contains (in this case the list of users). Without a dunder method, len(usergroup) would result in an error.


This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.