Properties For Computed Attributes

Expose computed values as attributes with property, keeping validation and derivation inside the class instead of at call sites.

PythonData Integrity

Code

pythonsnippet
35 lines
class Temperature:
    def __init__(self, celsius: float) -> None:
        self._celsius = float(celsius)

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

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

    @property
    def fahrenheit(self) -> float:
        # 计算属性:调用方当普通属性用
        return self._celsius * 9 / 5 + 32


def main() -> None:
    t = Temperature(21.5)
    print(f'{t.celsius:.1f}C = {t.fahrenheit:.1f}F')

    t.celsius = 30
    print(f'after set: {t.fahrenheit:.1f}F')

    try:
        t.celsius = -300
    except ValueError as exc:
        print('rejected:', exc)


if __name__ == '__main__':
    main()

Output

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

21.5C = 70.7F
after set: 86.0F
rejected: below absolute zero

How it works

Count the class Temperature and the functions __init__, celsius, fahrenheit and main as the entire surface area of Properties For Computed Attributes.

Failure is loud: ValueError aborts the current operation instead of degrading it.

What to watch for

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

Using it

The primary signature is def celsius(self) -> float

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

Key statements

def __init__(self, celsius: float) -> None:
    self._celsius = float(celsius)
def celsius(self, value: float) -> None:
    if value < -273.15:
        raise ValueError('below absolute zero')
    self._celsius = float(value)
def main() -> None:
    t = Temperature(21.5)
    print(f'{t.celsius:.1f}C = {t.fahrenheit:.1f}F')
    t.celsius = 30
    print(f'after set: {t.fahrenheit:.1f}F')
    try:
        t.celsius = -300
    except ValueError as exc:
        print('rejected:', exc)

Interactive Tools for This Topic

FAQ

Does the code validate its input?
`ValueError` is raised at the guard (`value < -273.15`), so invalid state never reaches the main logic.
What does Properties For Computed Attributes print when run?
The script runs standalone; its 2 labeled outputs include `after set:`, `rejected:`.