Practice mode Python

Which special method should a class define so that the built-in len() works on its instances?

Correct answer A. __len__

Explanation

len(obj) calls type(obj).__len__(obj), which must return an integer of zero or more. Defining __len__ also affects truth testing, since an object whose length is 0 is falsy when __bool__ is not defined. __length__, __size__ and __count__ are not part of the data model.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.