Reading history

Python @property, Setters and __slots__

6 min read 1 views

Use Python @property for computed and validated attributes, setters and deleters, and __slots__ to fix allowed attributes and save memory.

In Python you usually read and change an object’s data directly: student.marks = 84. But what if marks must stay between 0 and 100? Instead of writing get_marks() and set_marks() methods, Python offers @property: the attribute still looks like a plain variable, but a method runs behind it to check or calculate the value. This lesson also covers __slots__, which fixes the list of attributes an object may have.

In this lesson you will learn

  • Read-only computed attributes with @property
  • Validating new values with a setter
  • Converting units with a getter and setter pair, and the deleter
  • Restricting attributes with __slots__
  • When to use a property and when a plain attribute is enough

You should know classes and objects, encapsulation and decorators.

Validation With a Setter

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks            # goes through the setter below

    @property
    def marks(self):
        """Read like an attribute: s.marks"""
        return self._marks

    @marks.setter
    def marks(self, value):
        if not 0 <= value <= 100:
            raise ValueError(f"marks must be 0-100, got {value}")
        self._marks = value

    @property
    def grade(self):                  # computed, read-only
        return "A+" if self._marks >= 80 else "A" if self._marks >= 70 else "below A"

s = Student("Mitu", 76)
print(s.name, s.marks, s.grade)
s.marks = 84                          # looks like a plain assignment
print("after update:", s.marks, s.grade)

for bad in (120, -5):
    try:
        s.marks = bad
    except ValueError as e:
        print("ValueError:", e)

try:
    s.grade = "A+"
except AttributeError as e:
    print("AttributeError:", e)

try:
    Student("Rafi", 150)              # the constructor is checked too
except ValueError as e:
    print("constructor:", e)

Output

Mitu 76 A
after update: 84 A+
ValueError: marks must be 0-100, got 120
ValueError: marks must be 0-100, got -5
AttributeError: property 'grade' of 'Student' object has no setter
constructor: marks must be 0-100, got 150
  • @property above marks turns the method into a getter: writing s.marks calls it, without brackets.
  • @marks.setter defines what happens on s.marks = value. It checks the range and stores the number in self._marks. The underscore is a convention meaning “internal, use the property instead”.
  • In __init__, self.marks = marks also goes through the setter, so even a brand-new object cannot start with 150 marks.
  • grade has a getter but no setter, so it is a read-only computed attribute. It is worked out from the marks every time, so it can never be out of date. Assigning to it raises AttributeError.

Getter, Setter, Deleter and __slots__

import sys

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

    @property
    def fahrenheit(self):
        return self.celsius * 9 / 5 + 32

    @fahrenheit.setter
    def fahrenheit(self, f):
        self.celsius = (f - 32) * 5 / 9

    @fahrenheit.deleter
    def fahrenheit(self):
        print("  (cannot really delete; resetting to 0 C)")
        self.celsius = 0

t = Temperature(35)
print(f"{t.celsius} C = {t.fahrenheit} F")
t.fahrenheit = 212
print(f"set 212 F -> {t.celsius} C")
del t.fahrenheit
print("now", t.celsius, "C")

# __slots__: a fixed set of attributes, less memory, typos caught
class PointDict:
    def __init__(self, x, y):
        self.x, self.y = x, y

class PointSlots:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x, self.y = x, y

a, b = PointDict(1, 2), PointSlots(1, 2)
a.z = 3                                 # silently allowed
print("dict-based point got a new attribute z =", a.z)
try:
    b.z = 3
except AttributeError as e:
    print("AttributeError:", e)

dict_size = sys.getsizeof(a) + sys.getsizeof(a.__dict__)
slot_size = sys.getsizeof(b)
print("slots object is smaller:", slot_size < dict_size)

Output

35 C = 95.0 F
set 212 F -> 100.0 C
  (cannot really delete; resetting to 0 C)
now 0 C
dict-based point got a new attribute z = 3
AttributeError: 'PointSlots' object has no attribute 'z' and no __dict__ for setting new attributes
slots object is smaller: True
  • Temperature stores only Celsius. The fahrenheit property converts on the way out, and its setter converts back on the way in, so both units always agree.
  • @fahrenheit.deleter runs on del t.fahrenheit. Deleters are rare; here it resets the value instead of removing anything.
  • A normal object keeps its attributes in a dictionary, __dict__, so you can add new ones at any time. That also means a typo such as p.z instead of p.y silently creates a new attribute.
  • __slots__ = ("x", "y") tells Python the object will only ever have these two attributes. There is no __dict__, so a wrong name raises AttributeError, and each object uses less memory. That saving matters when you create millions of small objects.

Plain Attribute, Property or Method?

UseWhenExample
Plain attributeAny value is acceptableself.name = name
Property with setterValues need checking or convertingmarks, fahrenheit
Read-only propertyA quick value calculated from other datagrade, area
MethodSlow work, side effects or extra argumentssave(), send_email(to)

A good habit is to start with plain attributes. If you later need checks, turn the attribute into a property: code that uses s.marks does not need to change.

Common Mistakes

  1. Storing the value under the property’s own name, as in self.marks = value inside the marks setter. The setter calls itself forever and raises RecursionError. Store it in self._marks.
  2. Naming the setter differently from the getter. Both must have the same name, and the setter is decorated with @name.setter.
  3. Doing slow work in a property, such as a database query. Readers expect attribute access to be fast; use a method.
  4. Adding __slots__ everywhere. It is a memory optimisation; it also blocks dynamic attributes, which some libraries rely on.

Practice Exercises

Exercise 1. Write a Rectangle class with width and height and a read-only area property.

Show answer
class Rectangle:
    def __init__(self, width, height):
        self.width, self.height = width, height
    @property
    def area(self):
        return self.width * self.height

r = Rectangle(4, 5)
print(r.area)   # 20

Exercise 2. Add a phone property to a class whose setter accepts only 11-digit numbers starting with “01”.

Show answer
class Contact:
    def __init__(self, phone):
        self.phone = phone
    @property
    def phone(self):
        return self._phone
    @phone.setter
    def phone(self, value):
        if not (len(value) == 11 and value.isdigit() and value.startswith("01")):
            raise ValueError("phone must be 11 digits starting with 01")
        self._phone = value

Frequently Asked Questions

Does Python have private attributes?

Not strictly. A single underscore, _marks, is a polite convention meaning “internal”. A double underscore, __marks, triggers name mangling, which makes accidental access from subclasses harder but not impossible.

Can dataclasses use properties and slots?

Yes. A dataclass can define properties like any class, and @dataclass(slots=True) (Python 3.10 and later) creates __slots__ for you.

Summary

  • @property runs a method when an attribute is read, without changing how it looks.
  • A setter can check or convert values; without one, the property is read-only.
  • Store the real value under a different name, usually with an underscore.
  • __slots__ fixes the allowed attributes and saves memory.

Next: Python Decimal and Fractions.

Lessons are also marked complete when you click Next.

Leave a Reply

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