@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.
Code
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.0How 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.15short-circuits the flow with an earlyraisewhen 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.