Diving Deeper Into Magic Methods
00:00
You might be wondering, I’ve seen len
two different ways, sometimes with double underscores and sometimes without any underscores, like a function.
00:09 What’s the difference? The double-underscore version is the special method implemented in classes, and the non-underscore version is the built-in function that calls this special method.
00:23
The difference is in how these methods are typically used. When you use the .__len__
magic method directly, you are calling the magic method yourself.
00:34
However, when you use the built-in function, len()
, Python is implicitly calling the len
dunder method for you. This pattern of using a built-in function that internally calls a magic method applies to many operations in Python.
00:52
You’ll learn about them in the next lessons so let’s just stick with the len
example for now.
00:59
In this example, you have a BookCollection
class that takes a list of books as an argument. The __init__()
method initializes the object with the list of books storing it in the .self.books
attribute.
01:14
Next, you’re defining the len
magic method, which is for determining the length of the book collection. This method returns the length of the .self.books
list using Python’s built-in len
function.
01:29
Now, when you create a BookCollection
instance with books, Book 1
, Book 2
, and Book 3
, and then call len(collection)
, what happens behind the scenes is that Python implicitly calls the len
magic method of the collection object.
01:46
This method calculates the length of .self.books
, which in this case is three, and returns that value. So print(len(collection))
outputs three.
01:59
Why would I use the len
function and not just directly use the magic method? Well, the len
function is a more intuitive and user-friendly way.
02:08
You could directly call the magic method, but using the len
built-in function is considered more Pythonic because it’s more straightforward and more readable.
02:19
Python automatically calls the dunder method when you call len
, making your code cleaner and more understandable.
Become a Member to join the conversation.