Using len() and def __len__(self): to build a class

There is a huge difference.

The __len__() method is a hook method. The len() function will use the __len__ method if present to query your object for it’s length.

The normal API people expect to use is the len() method, using a .len attribute instead would deviate from that norm.

If the length of is not expected to change, you can always cache the length in an attribute and have .__len__() return that attribute.

class foo(object):
    def __init__(self, obs=None):
        if obs is None:  # provide a default if no list was passed in.
            obs = [] = obs
        self.max = max(obs)
        self.min = min(obs)
        self._data_len = len(obs)

    def __len__(self):
        return self._data_len

Leave a Comment