educative.io

@property decorator to set getters and setters in a python class

Hi,
I wanted to clarify a doubt related to getters and setters in a python class. As given in the course (https://www.educative.io/courses/learn-object-oriented-programming-in-python/m27v4PR52mG) getters and setters are class methods. While this in an option, I read about another option of using getters and setters (as properties) via @property decorator.

PFB the code an alternative code for the same example as used in the course: (this one is via @property decorator):

class User():

def __init__(self, username=None):  # defining initializer
    self.__username = username

@property    
def username(self):
    return (self.__username)


@username.setter    
def username(self, x):
    self.__username = x

Steve = User(‘steve1’)
print(‘Before setting:’, Steve.username)
Steve.username = ‘steve2’
print(‘After setting:’, Steve.username)

Question for the author: Out of the two approaches which one do you think is more suitable while responding in an interview?

Hi @Niladri, hope you are doing well.

I’m not the author, but your question is very common for Python developers. The simple answer is… there is no difference. You can use the decorator or the getter method, without any concern. I doubt a interviewer will say something about it.
That said, using the decorator is more “pythonic”, which means that you are following the language style and features for doing things (note that, pythonic, sometimes makes your code difficult to understand). In an interview I think that you can earn some points saying something like… “I could use a getter method, but I’m going to use this decorator cause it is more pythonic” OR “I’m using a getter here, cause I already used a setter and I think that my code became more coherent, but using a decorator can be a choice for a more pythonic style”.

Hope this helps!

Artur Baruchi

1 Like