__len__ in a Python class?
The purpose of __len__ in a Python class is to define how the built-in len() function should behave when called on an instance of that class.
Why it's used:
-
When you implement
__len__, you're telling Python how to compute the "length" of your custom object.
Example:
Key Points:
-
__len__must return an integer ≥ 0. -
If
__len__is not defined, callinglen()on the object will raise aTypeError.
It’s especially useful when creating custom container types that conceptually hold multiple items.

No comments:
Post a Comment