Member-only story

Understanding Python Properties: Classic vs. Decorator Syntax

Neural pAi
3 min readMar 25, 2023

--

Introduction:

In Python, properties are a convenient way to provide controlled access to an object’s attributes while implementing encapsulation. This article will compare two approaches to define properties in Python: the classic property() function and the modern decorator syntax. We will discuss the differences, advantages, and use cases of each approach.

Classic Property Function:

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

def get_name(self):
return self._name

def set_name(self,name):
self._name = name

def del_name(self):
del self._name

name = property(fget=get_name,fset=set_name,fdel=del_name)

p = Person('Nishant')
print(p.name)
delattr(p,"name")
p.name

The first example demonstrates the classic property() function, which consists of three methods (getter, setter, and deleter) and the property itself.

Code Explanation:

  • The class Person is defined with a constructor method __init__, which initializes the _name attribute.
  • The get_name, set_name, and del_name methods are defined to provide access, modification, and deletion of the _name attribute.

--

--

No responses yet