You’ll learn about the Python property decorator in this lesson, which is a pythonic approach to using getters and setters in object-oriented programming.
The @property decorator is a built-in decorator in Python that allows you to define properties without having to call the inbuilt function property(). Which is used to return a class’s property attributes from the getter, setter, and deleter parameters.
What Is The Difference Between Getters And Setters?
Setters: These are the methods that are utilized in the OOPS feature to set the value of private attributes in a class.
Here is a simple example of setting and getting properties in python.
## python property decorator example class ClassName: def __init__(self, val): self.__name = val # getter method to get the properties using an object def get_name(self): return self.__name # setter method to set the value 'name' using an object def set_name(self, val): self.__name = val ##
There are three methods in the above ClassName.
- __init__ is used to initialize a class’s attributes or properties.
- __name:- It is a private attribute.
- get_name: This function retrieves the values of the private attribute name.
- set_name: It is used to set the value of the name variable using a class object.
In Python, you can’t directly access the private variables. That’s why you included the getter method in your code.
Here is how the above example is interactive
## python property decorator example ## creating an object obj = ClassName("Jhon") ## getting the value of 'name' using get_name() method print(obj.get_name()) #Jhon ## setting a new value to the 'name' using set_name() method obj.set_name("Doe") print(obj.get_name()) #Doe ##
This is how private attributes, getters, and setters are implemented in Python.
Let’s look at how to use the @property decorator to implement the above class.
## python property decorator example class ClassName: def __init__(self, val): self.name = val @property def name(self): return self.__name @name.setter def name(self, val): self.__name = val ##
Without using any getter methods, @property is used to get the value of a private attribute. In front of the method where we return the private variable, we must add a decorator @property.
We use the @method_name.setter in front of the method to set the value of the private variable. It must be used as a setter.
How to hide the setter and getter methods and make them private?
Here is how you can do it.
## python property decorator example def __get_name(self): return self.__name def __set_name(self, val): self.__name = val ##
Video to explain the python property decorator
You’ve learned how to use Python to construct encapsulation and the differences between setter, getter, and property.
This article is written with the help of datacamp tutorials.