Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Hidden Gems in Python: Lesser-Known Tips & Tricks — Part 2

Sign upSign InSign upSign InMember-only storyJacob FerusFollowITNEXT--ShareWelcome to the second article in this series. If you haven’t read Part 1, that is fine; they aren’t directly connected. But if you want to read it, you can find it below:itnext.ioNow, let’s continue with Part 2!You’ve probably at some point used Decorators in Python. Decorators provide a clean and succinct way to modify or extend functions, but decorators can also be used for classes. Let’s quickly recap what a decorator is before showing how to apply it to classes with a practical example.Here’s an example of a decorator:The decorator my_decorator is applied with @my_decorator above def hello(). If you’ve never seen a decorator before, you may be confused, but it’s actually quite simple. All the decorator is doing is this:Hence, we are replacing the original hello with the return of the decorator method. Technically, you could return anything from my_decorator, for instance:Here hello isn’t even a method anymore, just a variable with the value "hello". As hello originally was a method though, it makes sense to return a callable. For this reason, the previous my_decorator-method returns a new method.Class decorators work the same way as function decorators, but instead of taking a function as input, they take a class as input. For instance:----ITNEXTLooking outside the box and making sense of the world using data.Jacob FerusinITNEXT--16Juntao QiuinITNEXT--10Daniel GlejznerinITNEXT--11Jacob FerusinITNEXT--7Ignacio de Gregorio--32Dominik PolzerinTowards Data Science--28Andy McDonaldinTowards Data Science--3Markham HeidinTHE NUANCE--64Tim Lou, PhDinTowards Data Science--9Rico FritzscheinLevel Up Coding--24HelpStatusWritersBlogCareersPrivacyTermsAboutText to speechTeams



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Hidden Gems in Python: Lesser-Known Tips & Tricks — Part 2

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×