Decorators in Python Classes

Hunter
2 min readOct 4, 2021

--

So, I just came across a new thing in Python! These were some basic decorators Python provides us, like the staticmethod , classmethod and the property decorators!

So in today’s article, we gonna discuss what are even these decorators and how we can use them to make our code look less messy!

Property Decorator in Python

The property decorator in action

So the property decorator is the easiest decorator of the 3 and you agree with me or not, but you are secretly using it in your code! So let’s look at some code so that you can learn more about it!

class Foo:
def __init__(self, data: dict) -> None:
try:
self.number = data.pop("number")
except KeyError:
self.number = None

So what we are doing in the above code is, checking if the key number is there in the data dict, and if it is not present, then the value of None is assigned to theself.number variable!

But, imagine you doing this in a biiiiig project with a thousands of keys. Your init would become more of a mess, than an init haha. So this is where the property decorator comes into play!

class Foo:
def __init__(self, data: dict) -> None:
self.data = data
@property
def number(self):
try:
return self.data.pop("number")
except KeyError:
return None

So, this is how u define a property using a property decorator! What we are doing in the code is making a property named number and setting its value as, either the value of the number key in the self.datadict, or None !

Both the piece of codes work the same way, the only difference property deco makes, is that it makes the code more readable! No clogging of the init method from now on :D

So this is it for today! I will write more about the other two decorators in the next blog so that it doesn’t get so overwhelming for newbies and so that you can practice this decorator first! I would love to hear how this decorator made your code more readable and your init less…. messy, in the comments section!

Contact me →

--

--

Hunter
Hunter

Written by Hunter

I am Hunter. Nice to meet you! I am a student and also a Python Coder. Stay away from me, I got a fetish for Python codes 😉

No responses yet