Menu
CoddyTech

Properties and Access Rules

Lesson 36 of 48 in Coddy's Python for C# Developers course.

Validate attribute assignment through properties and return readable object text.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

class Meter {
    private int level;
    public int Level {
        get => level;
        set { if (value < 0) throw new ArgumentOutOfRangeException(); level = value; }
    }
    public override string ToString() => $"level={level}";
}

Python

class Meter:
    def __init__(self, level):
        self.level = level
    @property
    def level(self):
        return self._level
    @level.setter
    def level(self, value):
        if value < 0:
            raise ValueError("negative level")
        self._level = value
    def __str__(self):
        return f"level={self.level}"

What changes

@property exposes a getter through attribute syntax, while @level.setter intercepts assignment, much like a C# property accessor. Initialization can use that setter too. _level marks an internal implementation detail by convention; it is not enforced C# private access. Double-leading underscores perform name mangling, not a security boundary. __str__ returns the human-readable string used by print, much like ToString.

Transfer mistake

Validate before storing so rejection leaves the prior value intact. The setter stores _level, not level, which would recursively call the setter. __str__ must return text rather than print it.

Your task

Implement Meter(level) with property level backed by _level and __str__ returning level=N. Construction and later assignment accept nonnegative integers; negative values must raise ValueError without changing existing state. Initialize through the setter. The driver reads an initial integer and a line of proposed levels; it prints ok or invalid followed by the current meter after each attempt. With no attempts it prints the initial meter once. An invalid initial level produces only invalid start.

challenge icon

Challenge

Beginner

Implement Meter(level) with property level backed by _level and __str__ returning level=N. Construction and later assignment accept nonnegative integers; negative values must raise ValueError without changing existing state. Initialize through the setter. The driver reads an initial integer and a line of proposed levels; it prints ok or invalid followed by the current meter after each attempt. With no attempts it prints the initial meter once. An invalid initial level produces only invalid start.

Editable implementation files: meter.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation modules.

Try it yourself

from meter import Meter

initial = int(input())
values = [int(x) for x in input().split()]
try:
    meter = Meter(initial)
except ValueError:
    print("invalid start")
else:
    for value in values:
        try:
            meter.level = value
            print("ok")
        except ValueError:
            print("invalid")
        print(meter)
    if not values:
        print(meter)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C# Developers

Practice on your own: Online Python compiler