@property: Setters

Combining Getters & Setters

@property: Getters



Introduction

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:

  1. Define a class and its attributes.
  2. Use @property before a method that will act as the getter for an attribute.
  3. Within the getter method, you can add any custom logic to compute the value of the attribute.
  4. When you access the attribute using dot notation, the getter method is automatically called.

Basic example

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.

Combined Examples

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.

  1. Getter Decorator (@property):
  2. Setter Decorator (@<attribute_name>.setter):