Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 27 / OBJECT-ORIENTED PYTHON

Properties and method kinds

Expose behaviour through a deliberate object API.

IntermediateTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain instance, class and static methods
  • Apply properties preserve an interface
  • Reason about exceptions versus silently fixing input
01

Instance, class and static methods

Method kinds differ in what Python supplies automatically: an instance method receives the object, a classmethod receives the class, and a staticmethod receives neither.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use instance methods for stateful work, classmethods for alternate construction that should honor subclasses, and static methods for helpers that fit the class's vocabulary but need no receiver. A free function is equally reasonable for an unrelated helper.

Words you will see

Bound method
A method reference that already carries its receiver.
cls
The conventional class parameter for a classmethod.
Alternative constructor
A named method that creates an instance from a different input form.

Choose the receiver you actually need

The initializer stores text on self. from_text receives cls because @classmethod changes how the function is bound. Calling SpecialLabel.from_text passes SpecialLabel as cls; return cls(...) therefore constructs the child type.

is_blank uses only its explicit text argument. @staticmethod prevents automatic self or cls injection. It can be called through Label without constructing an instance. A helper does not become faster or more secure merely because it is static.

Do not hard-code the base by accident

Returning Label(text.strip()) inside from_text would always make a base instance, even when called on SpecialLabel. That may be intentional in a factory, but it breaks the subclass-aware contract here.

strip removes surrounding whitespace, not internal spaces. Empty input becomes an empty label; this example allows that. Choose rejection if blank labels are invalid in your domain. Each constructor call creates independent object state; sharing the same immutable text is not a mutable-state leak.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. @classmethod

    Bind from_text to the receiving class.

  2. return cls(text.strip())

    Construct that class with trimmed text.

  3. label = SpecialLabel.from_text(" ready ")

    Pass SpecialLabel implicitly as cls.

  4. print(Label.is_blank(" "))

    Call the helper with no implicit receiver.

An instance method receives self; a classmethod receives cls and can create subclass-aware alternative constructors. A staticmethod receives neither automatically and is useful only when grouping it with the class improves understanding.

Predict before you run

Which argument is supplied automatically to from_text?

A constructor that respects subclassesPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Reveal hard-coded construction.

Try: Replace return cls(text.strip()) with return Label(text.strip()).

The type display becomes Label, showing the loss of subclass awareness.

Keep internal whitespace.

Try: Change the input to " ready now ".

Only the outer spaces disappear; the stored text is ready now.

Before you move on

If TinyLabel inherits SpecialLabel, what type does TinyLabel.from_text(' x ') return?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

TinyLabel, because cls is the class used for the call. The inherited method does not keep cls permanently bound to Label.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Properties preserve an interface

A property keeps attribute-style syntax while routing reads or writes through a rule. It is useful for cheap derived data or a local validation boundary.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

If width changes, a separately stored area could become outdated. A property derives the value on access. You need to understand normal methods and fields before treating a property as a managed attribute.

Words you will see

Getter
The function run when the property is read.
Setter
An optional function run when the property is assigned.
Derived value
A result calculated from other state rather than independently stored.

Attribute syntax, function work

@property wraps area so rectangle.area invokes the getter without parentheses. The getter reads current width and height. The first read multiplies three by four; the second reads the newly assigned width five and returns twenty.

There is no area field to synchronize. Since no setter is defined, rectangle.area = 99 raises AttributeError. That is a deliberate read-only public interface, not a limitation on updating width.

Use the least surprising surface

A local multiplication is a good property: cheap, deterministic and without visible side effects. A network fetch or costly recomputation should normally be an explicit method so the call site communicates work and possible failures.

This rectangle does not validate negative dimensions; it is an example of derivation, not a complete geometry model. Add a shared validation boundary if dimensions must be nonnegative. Do not silently clamp values while calling the result validation. Recap: properties can preserve syntax, but their behavior still needs a clear contract.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. @property

    Make area available through attribute access.

  2. return self.width * self.height

    Derive area from current state.

  3. rectangle.width = 5

    Change one underlying dimension.

  4. print(rectangle.area)

    Each occurrence calls the getter; the later result reflects width five.

A property provides attribute-style access backed by logic. Use it for validation or a cheap derived value; surprising expensive I/O behind a simple attribute read can make callers hard to reason about. A leading underscore signals convention, not a security boundary.

Conceptual property read dependency, not an instrumented execution trace

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Readrectangle.area requests the property's getter on Rectangle.
  2. DeriveThe getter reads rectangle.width and rectangle.height, then multiplies them.
  3. RefreshA later read uses current dimensions; no stored area needs synchronization.
Predict before you run

Why does the second area read change?

A derived rectangle areaPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Change the other dimension.

Try: Add rectangle.height = 2 before the last print.

The second area is 10.

Try writing the read-only attribute.

Try: Append rectangle.area = 99.

It raises AttributeError because area has no setter.

Before you move on

Does reading rectangle.area cache the first answer for later reads?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. A normal property runs its getter on every read. A cache needs a separate design and an invalidation policy when dimensions change.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Validate a managed attribute

A managed temperature attribute validates both construction and later updates through the same setter.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A model that checks only its constructor can become invalid on a later assignment. The original Temperature example keeps one public celsius attribute while concentrating its lower-bound rule in one place.

Words you will see

Backing attribute
The separate field, here _celsius, where the validated value is stored.
Absolute zero
The lower temperature boundary used by this model: -273.15 Celsius.
Atomic update
Here, an update that either succeeds or leaves the prior stored value unchanged.

Use the property from the constructor too

self.celsius = celsius invokes the property setter, even though it appears inside __init__. The setter rejects values less than -273.15. Only accepted values are written to self._celsius.

The getter returns the backing field. It must not return self.celsius, which would call itself repeatedly. Similarly, assigning self.celsius from inside the setter would recursively invoke the same setter.

Make limits and failures explicit

Temperature(20) validates and stores twenty, then the getter supplies 20 to print. Exactly -273.15 is accepted; a smaller value raises ValueError before any backing-field assignment.

This example checks an order comparison only. It does not validate every numeric case: bool and NaN need explicit policies in a production scientific API. The underscore is a signal to callers, not access control. Use explicit methods for actions with substantial work; use a simple dataclass if there are no meaningful managed transitions.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. self.celsius = celsius

    Route initialization through the public validation boundary.

  2. if value < -273.15:

    Reject strictly lower temperatures, but allow the boundary itself.

  3. self._celsius = value

    Write only after the rule passes.

  4. print(Temperature(20).celsius)

    Initialize, then read the accepted value through the getter.

Both construction and later assignment use the same validation boundary rather than exposing inconsistent state.

Predict before you run

Does the constructor invoke the setter?

Validate a managed attributePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Try the exact lower bound.

Try: Replace Temperature(20) with Temperature(-273.15).

The value is accepted and printed.

Try an invalid initial value.

Try: Use Temperature(-300).

It raises ValueError rather than constructing a usable invalid temperature.

Before you move on

After t = Temperature(20), does a failed t.celsius = -300 change the old value?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. ValueError is raised before _celsius is assigned, so t.celsius still returns 20 if the caller handles that exact error.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Method kinds describe what context an operation receives. Instance methods operate on one object's state, classmethods receive the actual class and can construct subclass-aware alternatives, and staticmethods receive neither automatically. The choice should clarify responsibility rather than function as a decorative annotation.

Follow the mechanism step by step

Attribute access to a method produces binding behaviour, while a property uses the descriptor protocol to mediate an attribute-like read or write. A property's setter can enforce a rule whenever callers assign through that interface. It does not make arbitrary access to underlying implementation state a security boundary.

Work through a concrete application

Use a temperature model to keep below-absolute-zero values out of the public update path. Route initialization through the same property so construction and later updates cannot disagree. For an alternative constructor from Fahrenheit, a classmethod can create cls rather than hard-coding the base class.

Failure cases and misleading shortcuts

Expensive network calls behind a property read can surprise callers who expect a cheap local value. A staticmethod that needs many instance fields may belong elsewhere. A leading underscore communicates convention, not access control; code and tests must still respect the intended public boundary.

Cost, ownership and alternatives

Properties can preserve an established attribute-style API while changing its implementation, but they also introduce hidden execution into lookup. Prefer a named method for actions with substantial cost or side effects. Keep validation errors distinct from automatic normalization so callers know whether their requested state was accepted.

Verify the contract

Test construction and every supported setter boundary, including equality at the minimum value and invalid types. Test alternative constructors through a subclass when subclass preservation is promised. Verify that a read does not mutate state or perform expensive work unless that behaviour is explicitly documented.

Transfer question: Should loading an object from a remote service be exposed as a property?

Usually a named operation makes latency, failure and cancellation clearer. A property may be acceptable for an already cached cheap value, but callers should not unknowingly trigger network I/O merely by inspecting an object's attributes.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Which method receives cls?
TRANSFER THE IDEA

Rebuild: Validate a managed attribute

Without copying the worked code, reproduce its observable contract: Both construction and later assignment use the same validation boundary rather than exposing inconsistent state. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Protect every temperature update

Return an object with a celsius property that accepts finite int or float values at least -273.15, but rejects bool and all other inputs.

The contract

  • Input and later celsius assignments accept finite int or float, excluding bool, at or above -273.15.
  • Return an object whose class defines a read/write celsius property. Preserve accepted numeric values without clamping.
  • Raise ValueError for invalid construction or assignment. A rejected update must leave the previous accepted value intact.
Protect every temperature updatePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. Managed initial value
    t = make_temperature(20)
    assert isinstance(type(t).celsius, property) and type(t.celsius) is int and t.celsius == 20
  2. Boundary and update
    t = make_temperature(-273.15)
    assert type(t.celsius) is float and t.celsius == -273.15
    t.celsius = 0
    assert type(t.celsius) is int and t.celsius == 0
  3. Invalid construction
    for value in (-274, True, "20", None, float("nan"), float("inf"), -float("inf")):
        try:
            make_temperature(value)
        except ValueError:
            pass
        else:
            assert False, repr(value)
    t = make_temperature(1.5)
    assert type(t.celsius) is float and t.celsius == 1.5
  4. Failed write preserves state
    t = make_temperature(8)
    for value in (-300, False, "x", float("nan")):
        try:
            t.celsius = value
        except ValueError:
            pass
        else:
            assert False, "invalid write accepted"
        assert type(t.celsius) is int and t.celsius == 8
  5. Independent receivers
    a, b = make_temperature(4), make_temperature(9)
    a.celsius = 6
    assert type(a.celsius) is int and a.celsius == 6 and type(b.celsius) is int and b.celsius == 9 and a is not b
  6. Repeated reads and writes
    t = make_temperature(0)
    t.celsius = 12.5
    assert type(t.celsius) is float and t.celsius == 12.5 and t.celsius == 12.5
    t.celsius = -273.15
    assert type(t.celsius) is float and t.celsius == -273.15
    Why does checking construction alone fail this contract?

    A later assignment could otherwise store an invalid value. Both paths use one setter, which checks before committing. The solution uses constant per-object storage and fixed-size validation work for these numeric inputs; it performs no I/O.

    GUIDED PRACTICE

    Make subclass-aware construction

    Return a Meter class with a classmethod from_text and staticmethod is_valid. Parse text into a new instance of the receiving class.

    The contract

    • Return a class Meter; Meter(value) stores value after requiring an exact nonnegative int, raising ValueError otherwise.
    • Meter.is_valid(value) is a staticmethod returning a bool for that exact-int rule.
    • Meter.from_text(text) is a classmethod: strip a string, parse with int, then construct cls. Empty, malformed and negative text raise ValueError. Separate instances own separate value fields.
    Make subclass-aware constructionPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. Method kinds and direct construction
      M = build_meter_class()
      assert isinstance(M, type) and isinstance(M.__dict__["from_text"], classmethod) and isinstance(M.__dict__["is_valid"], staticmethod)
      m = M(3)
      assert type(m) is M and type(m.value) is int and m.value == 3
    2. Trim and zero
      M = build_meter_class()
      m = M.from_text("  0  ")
      assert type(m) is M and type(m.value) is int and m.value == 0 and M.is_valid(0) is True
    3. Subclass-aware factory
      M = build_meter_class()
      class Child(M):
          pass
      m = Child.from_text(" 12 ")
      assert type(m) is Child and type(m.value) is int and m.value == 12
    4. Exact integer predicate
      M = build_meter_class()
      assert M.is_valid(2) is True and M.is_valid(-1) is False and M.is_valid(True) is False and M.is_valid(2.0) is False and M.is_valid("2") is False
    5. Parsing errors visible
      M = build_meter_class()
      for text in ("", " ", "two", "-1", "3.5"):
          try:
              M.from_text(text)
          except ValueError:
              pass
          else:
              assert False, text
      m = M.from_text("2")
      assert type(m) is M and type(m.value) is int and m.value == 2
    6. Instance ownership and constructor guards
      M = build_meter_class()
      a, b = M.from_text("2"), M.from_text("2")
      a.value = 7
      assert type(a) is M and type(b) is M and type(a.value) is int and a.value == 7 and type(b.value) is int and b.value == 2 and a is not b
      for value in (True, -1, 2.0):
          try:
              M(value)
          except ValueError:
              pass
          else:
              assert False, repr(value)
      Why must from_text use cls rather than a fixed Meter name?

      The receiver may be a subclass that needs its own instance. The inherited classmethod receives that class automatically. Parsing m characters takes O(m) text work plus integer-conversion cost; each result holds its own integer field.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: add a read-only converted view

      The requirement changes: celsius stays writable, but fahrenheit is a live read-only view, never independently stored state.

      The contract

      • Accept the same finite int/float, non-bool Celsius domain at least -273.15 as the guided exercise; reject invalid updates with ValueError before mutation.
      • Return an object with a read/write celsius property and a read-only fahrenheit property equal to celsius * 9 / 5 + 32.
      • fahrenheit assignment raises AttributeError. Reads must reflect current celsius; independent objects must not share state. Numeric comparisons may use a small floating-point tolerance.
      Transfer: add a read-only converted viewPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. Two properties, one source
        t = make_temperature_view(0)
        assert isinstance(type(t).celsius, property) and isinstance(type(t).fahrenheit, property) and type(t.celsius) is int and t.celsius == 0 and type(t.fahrenheit) is float and t.fahrenheit == 32.0
      2. Live conversion
        t = make_temperature_view(0)
        first = t.fahrenheit
        t.celsius = 100
        assert type(first) is float and first == 32.0 and t.celsius == 100 and type(t.fahrenheit) is float and t.fahrenheit == 212.0
      3. Read-only converted field
        t = make_temperature_view(20)
        try:
            t.fahrenheit = 999
        except AttributeError:
            pass
        else:
            assert False, "converted write accepted"
        assert t.celsius == 20 and type(t.fahrenheit) is float and t.fahrenheit == 68.0
      4. Lower bound
        t = make_temperature_view(-273.15)
        assert type(t.celsius) is float and t.celsius == -273.15 and type(t.fahrenheit) is float and abs(t.fahrenheit - (-459.67)) < 1e-9
      5. Rejected update and construction
        t = make_temperature_view(10)
        for value in (True, "4", -274, float("nan"), float("inf")):
            try:
                t.celsius = value
            except ValueError:
                pass
            else:
                assert False, "invalid update"
            assert t.celsius == 10 and type(t.fahrenheit) is float and t.fahrenheit == 50.0
            try:
                make_temperature_view(value)
            except ValueError:
                pass
            else:
                assert False, "invalid construction"
      6. Independent views
        a, b = make_temperature_view(0), make_temperature_view(20)
        a.celsius = 5
        assert type(a.celsius) is int and a.celsius == 5 and type(a.fahrenheit) is float and a.fahrenheit == 41.0 and type(b.celsius) is int and b.celsius == 20 and type(b.fahrenheit) is float and b.fahrenheit == 68.0 and a is not b
        What new error would storing Fahrenheit separately introduce?

        A Celsius update could leave the copied Fahrenheit value stale. Deriving it on each cheap local read avoids that extra invariant. The solution uses constant per-object storage and constant-size arithmetic beyond the costs of the supplied numeric values.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Attribute lookup explains surprises

        Properties live on the class and intercept ordinary attribute access. A same-named entry in an instance dictionary does not override a property.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Optional depth: knowing where an attribute is found helps explain managed fields and debugging surprises. It also shows why editing __dict__ is not a supported way to update a property.

        Words you will see

        Descriptor
        An object on a class that controls attribute access through special methods.
        Instance dictionary
        The mapping holding ordinary attributes for instances that support __dict__.
        Precedence
        The order Python uses to choose between competing attribute sources.

        Two places can hold the same name

        Gauge.value is a property object stored on the class. gauge.__dict__["value"] is a plain dictionary entry on this instance. The two can coexist. For ordinary property lookup, the class's data descriptor takes precedence over that instance entry.

        Reading gauge.value invokes the getter and returns _value, which is seven. Reading the dictionary explicitly returns ninety-nine. The latter bypasses ordinary attribute lookup and does not prove that the getter changed.

        Use the intended boundary

        A property without a setter still intercepts writes and rejects ordinary gauge.value = 99. A leading underscore alone would not have that behavior. Custom __getattribute__ can change lookup rules, but this lesson assumes ordinary Python object lookup.

        Inspecting __dict__ is useful for learning, not a recommendation to bypass model rules in application code. Prefer the public property or an explicit update method. Not all objects expose __dict__, for example some slotted objects; do not make an instance dictionary a universal API requirement.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. gauge.__dict__["value"] = 99

          Insert an ordinary instance entry directly.

        2. print(gauge.value)

          Normal lookup still uses the property getter.

        3. print(gauge.__dict__["value"])

          Direct dictionary lookup sees the inserted value.

        4. print(isinstance(Gauge.value, property))

          Class access exposes the property object for inspection.

        Properties are descriptors on the class and participate in attribute lookup. Class attributes and instance dictionaries are not interchangeable. Avoid relying on monkey patches or hidden side effects that make the public contract depend on lookup accidents.

        Predict before you run

        Which value does gauge.value read?

        A property wins over an instance keyPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Edit the actual backing field.

        Try: Replace the dictionary insertion with gauge.__dict__["_value"] = 12 and remove the direct value-key print.

        The property read becomes 12.

        Observe the public write policy.

        Try: Replace the dictionary insertion with gauge.value = 99.

        AttributeError is raised because the property has no setter.

        Before you move on

        What happens if _value is changed to 12 in the dictionary instead?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        The getter returns 12, because its implementation explicitly reads self._value. The competing public value entry would still be ignored by the property.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Exceptions versus silently fixing input

        Validation rejects input that violates a rule. Normalization changes an accepted spelling into a standard form. Silent repair is neither unless the contract says so.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Optional depth: bool is a subclass of int in Python, so isinstance(True, int) is True. Some domains want counts to be exact nonnegative integers and must reject booleans deliberately.

        Words you will see

        Normalization
        A documented conversion such as removing surrounding whitespace.
        Clamping
        Replacing an out-of-range value with the nearest allowed boundary.
        Exact type policy
        Accepting only a specific type rather than all its subclasses.

        Check type before numeric comparisons

        The setter uses type(proposed) is not int to reject bool, strings and floats. or short-circuits: if the type is wrong, Python does not evaluate proposed < 0. If the type is int, the second condition rejects negative values.

        Only after both conditions pass is _value assigned. level.value = True therefore raises the specific ValueError, the handler displays it, and four remains stored.

        Do not erase evidence of a bad request

        Replacing a negative count with zero would produce a plausible-looking record while hiding the invalid request. Reject it unless clamping is explicitly part of the domain. Parsing a numeric string is another boundary and should be named rather than silently mixed into this setter.

        Exact int is intentionally strict and excludes custom integer subclasses too. Use isinstance when the contract welcomes such subclasses and explicitly excludes bool if necessary. Constant-size local validation is suitable for a property; remote validation belongs in an explicit operation with visible failure behavior.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. if type(proposed) is not int or proposed < 0:

          Validate the exact-type and range contract before storing.

        2. self._value = proposed

          Commit a successful update.

        3. level.value = True

          Trigger the intentionally rejected bool case.

        4. print(level.value)

          Read the unchanged prior valid state.

        Reject an invalid value with an explicit error unless normalisation is part of the documented contract. Clamping a temperature silently would hide bad input. Prefer a plain dataclass when there are no state transitions to protect.

        Predict before you run

        What would level.value = 0 do?

        Reject instead of clampingPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Test a numeric string.

        Try: Replace True with "4".

        It is rejected by the type check before any string-to-number comparison occurs.

        Accept the boundary.

        Try: Replace True with 0.

        No error message is printed and the final value is zero.

        Before you move on

        Does level.value = 4.0 pass because 4.0 == 4?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. Equality does not make the types identical. The contract accepts exact int, so a float raises ValueError even when its numeric value is whole.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.