In Python, the @property decorator is used to create "getter" methods for class attributes. It allows you to access and manipulate an attribute's value as if it were a regular property, but behind the scenes, you can add custom logic for getting the value.
Here's a simple explanation of how it works:
@property before a method that will act as the getter for an attribute.class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
print("Getting the radius...")
return self._radius
@radius.setter
def radius(self, value):
print("Setting the radius...")
if value < 0:
raise ValueError("Radius cannot be negative.")
self._radius = value
circle = Circle(5)
print(circle.radius) # Output: Getting the radius... 5
circle.radius = 8 # Output: Setting the radius...
print(circle.radius) # Output: Getting the radius... 8
In this example, we have a Circle class with a private attribute _radius. We use the @property decorator to create a getter method for the radius attribute, and the @radius.setter decorator to define a setter method. When you access circle.radius, it calls the getter method, and when you set circle.radius, it calls the setter method, allowing you to perform any necessary checks or computations.
Certainly! In Python, the "getter" and "setter" decorators are used to create properties with custom behavior for getting and setting attribute values in a class. They are part of the @property decorator, which allows you to define getter and setter methods for attributes, providing controlled access to the class data.
@property):
@property decorator before the method definition.@<attribute_name>.setter):
@<attribute_name>.setter decorator before the method definition, where <attribute_name> should match the name of the corresponding getter method.