🐍

Property Decorator in Python

Jul 9, 2024

Property Decorator in Python

Introduction

  • The property decorator allows defining a method as a property.
  • Access methods like attributes.
  • Benefits: Add additional logic when reading, writing, or deleting attributes.

Components of Property Decorator

  • getter method: To read the attribute.
  • setter method: To write the attribute.
  • deleter method: To delete the attribute.

Example: Rectangle Class

Constructor

  • Initialize with width and height. def __init__(self, width, height): self._width = width self._height = height

Creating Rectangle Object

  • Creating a rectangle object and printing attributes: rectangle = Rectangle(3, 4) print(rectangle.width) # Access width attribute print(rectangle.height) # Access height attribute

Private Attributes

  • Prefix attributes with _ to make them private: self._width = width self._height = height
    • Indicates attributes meant to be internal and protected.
    • Access through getter methods.

Getter Methods

  • Define getter methods using @property decorator: @property def width(self): return f"{self._width:.1f} cm" @property def height(self): return f"{self._height:.1f} cm"

Setter Methods

  • Define setter methods using attribute_name.setter decorator: @width.setter def width(self, new_width): if new_width > 0: self._width = new_width else: print("Width must be greater than zero") @height.setter def height(self, new_height): if new_height > 0: self._height = new_height else: print("Height must be greater than zero")

Deleter Methods

  • Define deleter methods using attribute_name.deleter decorator: @width.deleter def width(self): del self._width print("Width has been deleted") @height.deleter def height(self): del self._height print("Height has been deleted")

Summary

  • Property decorator (@property) allows methods to be accessed as attributes.
  • Benefits:
    • Adding logic when reading, writing, and deleting.
  • Getter, setter, and deleter methods provide control over attribute access.