Member-only story
Managing Attributes with Python’s Property Decorator: Creating Read-Only and Read-Write Properties with Input Validation
Introduction
Python’s property
decorator allows you to define methods that act like attributes, providing a way to manage how the attribute is accessed and modified. The property decorator can be used to make a method read-only, write-only, or read-write, and can also be used to validate inputs or perform computations on the fly.
In this article, we’ll explore how to use the property
decorator in Python to create read-only and read-write properties, and perform input validation.
Creating a read-only property
Let’s start with a simple example: a class that has a name
attribute. We can make this attribute read-only by using the property
decorator as follows:
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
In this updated version of the Person
class, the name
attribute is now accessed through a method called name()
, which is decorated with the @property
decorator. This means that the name
method now acts like an attribute, and can be accessed using dot notation:
p = Person('Alice')…