Programming with Python · free preview

Objects at the Next Level

Separate class state from instance state, guard attributes with properties, implement dunder methods, and cut boilerplate with dataclasses.

1. Overview

Overview

2. Class Attributes vs Instance Attributes

Class Attributes vs Instance Attributes

3. Guarding Values with Properties

Guarding Values with Properties

4. Dunder Methods

Dunder Methods

5. Dataclasses

Dataclasses

6. A Validated Temperature

A Validated Temperature

7. A Dataclass Inventory

A Dataclass Inventory

8. Methods bound to the class

Methods bound to the class

9. Predict rejected assignment state

t = Temperature(37.0) succeeds, then t.celsius = 46.0 raises ValueError. What is t.celsius afterward?

10. Validating a Reading at construction and assignment

Run the property-based Reading class with a valid construction, a rejected later assignment, and a final read of the stored value. Predict every printed line.

Example. Validating a Reading at construction and assignment

Problem. Run the property-based Reading class with a valid construction, a rejected later assignment, and a final read of the stored value. Predict every printed line.

Correct solution.

python
class Reading:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value > 45:
            raise ValueError("implausible temperature")
        self._celsius = value

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

r = Reading(37.0)
print(r.celsius, round(r.fahrenheit, 1))
try:
    r.celsius = 46.0
except ValueError as error:
    print("blocked:", error)
print(r.celsius)

关键提醒。

Input is the construction value 37.0, the attempted assignment 46.0, and the final read of r.celsius.

Trace:

  1. Reading(37.0) calls the setter because __init__ assigns to self.celsius; 37.0 > 45 is false, so _celsius becomes 37.0.
  2. r.fahrenheit reads the property and computes 37.0 * 9 / 5 + 32, which rounds to 98.6.
  3. r.celsius = 46.0 enters the same setter, 46.0 > 45 is true, and the ValueError is raised before _celsius changes.
  4. The final print(r.celsius) therefore still shows 37.0.

Expected output:

Output

37.0 98.6
blocked: implausible temperature
37.0

11. Retrieval practice

Write the Temperature class whose celsius setter rejects values below 30 or above 45, construct Temperature(37.0), then assign 46.0, then read t.celsius. What exact lines appear, and why?

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

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        # complete the validation

t = Temperature(37.0)
try:
    t.celsius = 46.0
except ValueError as error:
    print("blocked:", error)
print(t.celsius)

Use the exception message out of range: {value}.

12. Mastery check

Define a @dataclass called Delivery with fields item: str and count: int. Add validation in __post_init__ that rejects a negative count with ValueError. Create Delivery("gloves", -1), then create Delivery("gloves", 5) and compare it with an equal Delivery. Give the code and exact resulting behavior.

python
from dataclasses import dataclass

# complete Delivery here

invalid = Delivery("gloves", -1)
valid = Delivery("gloves", 5)
equal = Delivery("gloves", 5)
print(valid)
print(valid == equal)

Practice this interactively

Free account · instant grading · spaced review that schedules itself.

Start this course for free