Just curious,
Is there any difference (advantages and disadvantages) between using len()
or def __len__()
when I build a class? And which is the best Python style?
class foo(object): def __init__(self,obs=[]) self.data = obs self.max = max(obs) self.min = min(obs) self.len = len(obs)
or
class foo(object): def __init__(self,obs=[]) self.data = obs self.max = max(obs) self.min = min(obs) def __len__(self): return len(self.data)
object.__len__(self) The Python __len__ method returns a positive integer that represents the length of the object on which it is called. It implements the built-in len() function. For example, if you call len(x) an object x , Python internally calls x.
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 self.
Answer. The len() function will attempt to call a method named __len__() on your class. This is one of the special methods known as a “dunder method” (for double underscore) which Python will look for to perform special operations. Implementing that method will allow the len() call to work on the class.
The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.
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 self.data
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 = [] self.data = obs self.max = max(obs) self.min = min(obs) self._data_len = len(obs) def __len__(self): return self._data_len
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With