What is the purpose of the @property decorator in Python?
Python > Python Classes and Objects > Python Decorator
331
Answer:
The @property
decorator in Python is used to create getter and setter methods for class attributes, allowing them to be accessed and modified as if they were ordinary instance variables, while providing a level of control over their access and modification.
The @property
decorator is used to define a method as a "getter" for a class attribute. The method is called whenever the attribute is accessed, allowing for additional processing or validation to be performed. The @property
decorator can also be used in conjunction with the @setter
decorator to define a method as a "setter" for a class attribute. The setter method is called whenever the attribute is assigned a new value, allowing for additional processing or validation to be performed.
For example, consider the following code:
class Rectangle: def __init__(self, width, height): self._width = width self._height = height @property def width(self): return self._width @width.setter def width(self, value): if value <= 0: raise ValueError("Width must be positive") self._width = value @property def height(self): return self._height @height.setter def height(self, value): if value <= 0: raise ValueError("Height must be positive") self._height = value def area(self): return self._width * self._height
In this example, the @property
decorator is used to define getter and setter methods for the width
and height
attributes of the Rectangle
class. The getter methods return the values of the attributes, while the setter methods validate the input and set the values of the attributes.
By using the @property
decorator, the width
and height
attributes can be accessed and modified as if they were ordinary instance variables, while providing additional control over their access and modification. This makes the code more readable and maintainable, and helps to prevent programming errors by validating input and enforcing constraints on the data.
This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.