Yes, the len() function can be used with custom objects in Python, but the custom class must implement the __len__() method. This method should return an integer representing the size or count of elements in the object.
Here’s an example of how to implement this:
class MyCollection:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
# Example usage
collection = MyCollection([1, 2, 3, 4])
print(len(collection)) # Output: 4
In this example, the MyCollection class has a __len__() method that returns the length of the items list. Thus, you can use len() on instances of MyCollection.
