A smooth sea never made a skilled sailor. - Franklin D. Roosevelt
Hi Pythonistas, a new week, a new 'bite' of Python coding! We wrote an article for Dan Bader's Python blog: Enriching Your Python Classes With Dunder (Magic, Special) Methods. We hope you like it. To put dunders into practice we dedicate this week's code challenge to it.
To quote from our guest post:
In Python, special methods are a set of predefined methods you can use to enrich your classes. They are easy to recognize because they start and end with double underscores, for example
__str__. .... This elegant design is known as the Python data model and lets developers tap into rich language features like sequences, iteration, operator overloading, attribute access, etc.
Basic: take an existing class you wrote or write one from scratch (other than Account), implementing at least construction, object representation and iteration using special methods.
Intermediate to Advanced: implement one or more of the other language features discussed in the article: operator overloading, method invocation, context management. And/or look at the data model documentation and try to implement one or more dunders not discussed in the article: attribute access, metaclasses or coroutines for example.
Bonus: write some tests to verify the dunders you have implemented behave as expected.
This doc also provides you with instructions how you can submit your code to our community branch via a Pull Request (PR). We will feature your PRs in our end-of-the-week challenge review (previous editions).
Note that when you do a PR you should see a short template asking for some meta data. We implemented that as part of code challenge 23 to track our challenges and over time enrich our Challenges page.
Last but not least: there is no best solution, only learning more and better Python. Good luck!
Keep Calm and Code in Python!
-- Bob and Julian
Do you want to get 250+ concise and applicable Python tips in an ebook that will cost you less than 10 bucks (future updates included), check it out here.
"The discussions are succinct yet thorough enough to give you a solid grasp of the particular problem. I just wish I would have had this book when I started learning Python." - Daniel H
"Bob and Julian are the masters at aggregating these small snippets of code that can really make certain aspects of coding easier." - Jesse B
"This is now my favourite first Python go-to reference." - Anthony L
"Do you ever go on one of those cooking websites for a recipe and have to scroll for what feels like an eternity to get to the ingredients and the 4 steps the recipe actually takes? This is the opposite of that." - Sergio S