Last modified: Nov 27, 2026

Python Class Property Setter Guide

A property setter lets you control how an attribute gets a new value. It runs code every time you assign to that attribute.

This guide explains how setters work. It shows the syntax, real examples, and common mistakes. You will also see how setters fit into clean class design.

What Is a Property Setter?

In Python, a property turns a method into an attribute-like access point. A getter reads the value. A setter writes the value.

The setter is defined with the @name.setter decorator. It must share the same name as the getter property.

When you assign a value, Python calls the setter instead of changing the attribute directly. This gives you a place to validate, transform, or log data.

If you are new to properties, the Python class level property guide is a good starting point before diving into setters.

Basic Setter Syntax

Here is a simple example. The setter checks that the value is positive before storing it.


class Product:
    def __init__(self, price):
        self._price = 0
        self.price = price  # calls the setter

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("Price cannot be negative")
        self._price = value

p = Product(100)
print(p.price)  # read via getter
p.price = 250   # write via setter
print(p.price)

100
250

Notice the underscore in self._price. It signals that the attribute is internal. The public interface is price.

This naming pattern is common. It avoids a recursion problem that we will cover later.

Why Use a Setter?

Setters give you control over assignment. You can reject bad data. You can clean input. You can update related fields.

Without a setter, any value can be assigned. That can break your object's state.

Consider a temperature class. A setter could convert Fahrenheit to Celsius automatically. The rest of the class then always works with one unit.

Setters also keep your public API stable. You can add validation later without changing how callers use the class.

To decide when this is worth it, read about when to use property in Python.

Getter and Setter Together

A property usually pairs a getter with a setter. The getter returns the stored value. The setter updates it.

You can also define a getter alone. That makes the attribute read-only. Assigning to it raises an AttributeError.


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

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value <= 0:
            raise ValueError("Radius must be positive")
        self._radius = value

c = Circle(5)
print(c.radius)
try:
    c.radius = -2
except ValueError as e:
    print(e)

5
Radius must be positive

The setter protects the object. Invalid values never enter the internal state.

The Recursion Trap

A common beginner mistake is assigning to the property name inside the setter. This causes infinite recursion.


class Bad:
    @property
    def value(self):
        return self.value

    @value.setter
    def value(self, v):
        self.value = v  # RecursionError!

The fix is simple. Store data in a private attribute such as self._value. The setter then updates that attribute.

This is why the underscore convention matters. It separates the public property from the internal storage.

Understanding instance references helps here. If you are unsure how self works, see what is self in Python explained.

Validation Inside Setters

Validation is the most popular use of setters. You can check type, range, format, or length.


class User:
    def __init__(self, email):
        self.email = email

    @property
    def email(self):
        return self._email

    @email.setter
    def email(self, value):
        if not isinstance(value, str):
            raise TypeError("Email must be a string")
        if "@" not in value:
            raise ValueError("Invalid email address")
        self._email = value.strip().lower()

u = User("  [email protected] ")
print(u.email)

[email protected]

Here the setter both validates and normalizes. The stored value is always clean and consistent.

Keep validation rules in one place. The setter is the natural home for them.

Computed and Dependent Properties

Setters can update related attributes. This keeps the object in sync.


class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        if value <= 0:
            raise ValueError("Width must be positive")
        self._width = value

r = Rectangle(4, 5)
print(r.area)
r.width = 10
print(r.area)

20
50

The area updates automatically because it is computed on read. No manual refresh is needed.

For more on how properties differ from plain attributes, read Python class property vs attribute.

Setters and Inheritance

Subclasses can override a setter. They can also extend it by calling the parent setter with super().


class Account:
    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("Balance cannot be negative")
        self._balance = value

class SavingsAccount(Account):
    @Account.balance.setter
    def balance(self, value):
        super(SavingsAccount, type(self)).balance.fset(self, value)
        print(f"Balance set to {value}")

Overriding setters is useful but can get complex. Keep the logic small and predictable.

Common Mistakes to Avoid

Mistake 1: Using the property name inside the setter. This causes recursion.

Mistake 2: Forgetting the getter. A setter alone does not create a readable property.

Mistake 3: Doing heavy work in a setter. Setters should be fast and focused.

Mistake 4: Hiding side effects. If a setter changes other state, document it clearly.

Also avoid duplicating validation in many places. Route all writes through the setter.

Setter vs Plain Attribute

Not every attribute needs a setter. Plain attributes are simpler and faster.

Add a setter only when you need behavior on assignment. That means validation, conversion, or side effects.

Premature setters add noise. Start simple. Add a property when a real need appears.

This keeps classes readable and easy to maintain.

Practical Checklist

Use this quick checklist when writing a setter:

1. Store data in a private attribute like self._name.

2. Validate input early and raise clear errors.

3. Keep the setter short and single-purpose.

4. Pair every setter with a getter of the same name.

5. Test edge cases such as empty strings and negative numbers.

Following these rules prevents most setter bugs.

Conclusion

A Python property setter gives you safe, controlled writes to class attributes. It runs custom logic on every assignment.

Use the @property decorator for the getter and @name.setter for the setter. Always store values in a private attribute to avoid recursion.

Setters shine for validation, normalization, and keeping related state in sync. They also keep your public API stable over time.

Start simple. Add setters only when assignment needs behavior. With clear naming and small methods, your classes stay clean and predictable.