@property Setters Validate Every Assignment

A @property setter turns ordinary assignment into a validation point, so out-of-range values are rejected even during construction.

PythonData Integrity

Code

pythonsnippet
30 lines
class Sensor:
    def __init__(self, celsius: float = 0.0):
        # 构造期的赋值同样走 setter:校验从对象诞生那一刻就生效
        self.celsius = celsius

    @property
    def celsius(self) -> float:
        return self._celsius

    @celsius.setter
    def celsius(self, value: float) -> None:
        if value < -273.15:
            raise ValueError("celsius below absolute zero: " + str(value))
        self._celsius = float(value)

    @property
    def fahrenheit(self) -> float:
        return self._celsius * 9 / 5 + 32


sensor = Sensor(25.0)
print("constructed:", sensor.celsius, sensor.fahrenheit)

sensor.celsius = -40.0  # 赋值语法,实际经过 setter 校验
print("after set  :", sensor.celsius, sensor.fahrenheit)

try:
    sensor.celsius = -300.0
except ValueError as exc:
    print("rejected   :", exc)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

constructed: 25.0 77.0
after set  : -40.0 -40.0
rejected   : celsius below absolute zero: -300.0

How it works

@property Setters Validate Every Assignment reduces to the class Sensor and the functions __init__, celsius and fahrenheit.

The failure path is explicit — ValueError is raised when the guard condition holds.

What to watch for

  • The guard value < -273.15 short-circuits the flow with an early raise when its condition holds.

Putting it to use

Entry signature: def celsius(self) -> float

The demo output is labeled (constructed:, after set :, rejected :), so every printed line maps back to its originating operation.

Import celsius from the file and call it — the rest of the code is implementation detail.

Core lines

def celsius(self, value: float) -> None:
    if value < -273.15:
        raise ValueError("celsius below absolute zero: " + str(value))
    self._celsius = float(value)
def __init__(self, celsius: float = 0.0):
    # 构造期的赋值同样走 setter:校验从对象诞生那一刻就生效
    self.celsius = celsius
def fahrenheit(self) -> float:
    return self._celsius * 9 / 5 + 32

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code throws `ValueError` — the guard `value < -273.15` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `__init__`, `celsius`, `fahrenheit` at load time.