Python property(): Create Managed Attributes in a Class

The property() function creates managed attributes in a class, allowing control over getting, setting, and deleting properties. It’s useful for encapsulating data, adding validation, and making attributes read-only.

Example

class Person:
    def __init__(self, name):
        self._name = name  # Private variable

    def get_name(self):
        return self._name

    def set_name(self, value):
        if not isinstance(value, str):
            raise ValueError("Name must be a string")
        self._name = value

    name = property(get_name, set_name)  # Creating a managed attribute

p = Person("Alice")
print(p.name)  # Output: Alice
p.name = "Bob"
print(p.name)  # Output: Bob

This manages the name attribute with controlled access.

Syntax

property(fget=None, fset=None, fdel=None, doc=None)
  • fget → Function to get the value (getter).
  • fset → Function to set the value (setter).
  • fdel → Function to delete the value (deleter).
  • doc → Optional docstring.
  • Returns → A property object.

1. Creating Read-Only Properties

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius  # No setter makes it read-only

c = Circle(5)
print(c.radius)  # Output: 5
c.radius = 10  # AttributeError: can't set attribute

@property makes radius read-only.

2. Adding Validation with property()

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    def get_celsius(self):
        return self._celsius

    def set_celsius(self, value):
        if value < -273.15:
            raise ValueError("Temperature cannot be below absolute zero")
        self._celsius = value

    celsius = property(get_celsius, set_celsius)

t = Temperature(25)
print(t.celsius)  # Output: 25
t.celsius = -300  # ValueError: Temperature cannot be below absolute zero

Prevents invalid values from being assigned.

3. Using @property with Getters and Setters

class Square:
    def __init__(self, side):
        self._side = side

    @property
    def side(self):
        return self._side

    @side.setter
    def side(self, value):
        if value < 0:
            raise ValueError("Side length cannot be negative")
        self._side = value

s = Square(4)
print(s.side)  # Output: 4
s.side = -2  # ValueError: Side length cannot be negative

Using @property makes the code cleaner and easier to read.

Key Notes

  • Encapsulates class attributes with control over access.
  • Use @property for read-only attributes.
  • Supports validation before setting values.
  • Allows deleting attributes with @property.deleter.

By using property(), you can ensure controlled access to attributes, add validation, and prevent unwanted modifications. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top