In the previous lesson, I showed you how
len() works with multi-dimensional NumPy arrays and Panda’s DataFrames. In this lesson, I’ll show you how an object can report back its length through the
__len__() special method. Everything in Python is a class.
In the top half of the window here is a class called
Inventory. It behaves kind of like a dictionary in that it stores keys and values. It expects the values to be an integer specifying how many items of a given name there are. The
__len__() method then returns the total number of items in the inventory.
Lines three through eight initialize the object. The contents of the inventory are stored in a dictionary called
self.content. Initial content can be passed into
Inventory when it is created, and lines six through eight copy that initial data into the content dictionary. Note the use of
initial=None on line three. Default arguments in Python should only ever be static values.
Using a dynamic value like an empty dictionary can cause surprising side effects. If you did that, the second time you created
Inventory, you’d get data from the first time you created
Inventory. Best not to do that.
Line 13 is the definition of
__repr__(). This is a special method returning a string representation of the object.
__repr__() and its cousin
__str__() are used by Python to help show the string representations of objects in a couple different cases. They’re commonly used when you’re debugging.
__repr__() is the one that’s called by the REPL to show its contents, and seeing as I’m going to be demoing this in the REPL, I implemented this so you could see the underlying content of the Inventory.
And finally, the magic you came here for is on lines 16 and 17. This is the
__len__(). This method uses
sum() to count up all of the items inside of the internal dictionary and returns that value.
showing the value. This is where the
__repr__() method is called. And now what you came here for:
len() Sure enough, three and five is eight. Aren’t computers wonderful? In the olden days, you would have had to use your fingers or something to do that kind of math.
__len__() has added up the number of apples and the number of pears and returned the total result. I think I missed out on an opportunity here about apples and oranges being compared. By implementing
__len__(), you have also by default made your object truthy.
And this time you get
__len__() gives you both the length and truthiness. If you don’t like this behavior, you can also override
__bool__() and get it to do what you want instead.
Become a Member to join the conversation.