27 likes
路
732 reads
6 comments
Dunders, or magic methods, or double-underscore methods, are definitely one of the great things in Python: once you start understanding how Python works, you can really leverage these and make your code much more pythonic.
Adding some dunders to your custom classes transform them to iterables, or other useful types. e.g. If you add __len__
and __getitem__
to your class and you can make use it like an interable. Add an __enter__
and an __exit__
and you can use your custom context in a with ...as ...:
block (and get all the benefits, like the guarantee the __exit__
will be called even if an exception is raised.
The 芦Fluent Python禄 book really introduced me to these a while ago, and it was the big change.
For instance, once you get this, you understand why Python has a len(obj)
built in function rather than a obj.len()
method: any object which implements a __len__(self):
method can be called with len(obj)
, and this __len__
is also used for other constructs (like the iterable). When I started learning Python, I was always bugged by this len()
requiring the object has an argument. Once I understood the dunder paradigm and how it helps the developer implement behaviors using composition, it all made sense and became much more easier to remember (and leverage!)
Recommended reading: Fluent Python (from O鈥橰eilly)
And Raymond Hettinger鈥檚 芦Beyond PEP8禄 talk with live code refactoring is a great example on how to leverage dunders to make the code more pythonic, and hide the boilerplate to make the code shorter and focused on the business logic. Really a recommended talk! : youtube.com/watch?v=wf-BqAjZb8M
Well, TIL for me as well. I never really imagined they'd had a name 馃榿
Cool to know.
Its nice to know these many features. Love this. Thanks Walmartone
TIL: Dunders
This post is really amazing walmartone.tech
Wait, is Dunder what the type of method is called? I thought it just meant "double underscore". Like "dunder init dunder." I can't say "dunder" with a straight face lol.
Also would it be camelCase between the dunders, or snake_case? Asking the important questions here.