Menu
CoddyTech

Properties and Object Text

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

Expose a validated attribute without making callers switch to a setter method, and give the object a readable string for ordinary output. A property lets the implementation enforce a rule whenever the public attribute is assigned.

JavaScript

class Dial {
  constructor(value) { this.value = value; }
  get value() { return this._value; }
  set value(v) {
    if (v < 0) throw new RangeError("negative");
    this._value = v;
  }
}
console.log(new Dial(3).value);

Python

class Dial:
    def __init__(self, value):
        self.value = value
    @property
    def value(self):
        return self._value
    @value.setter
    def value(self, v):
        if v < 0:
            raise ValueError("negative")
        self._value = v
print(Dial(3).value)

What changes

Both complete examples print 3 and reject a negative assignment. In Python, @property makes the following getter available through attribute access; @value.setter connects a setter for the same name. This is the focused decorator pattern you need here, without writing a decorator yourself. Use a separate backing attribute such as _value. A leading underscore asks callers to treat a name as internal; it does not enforce privacy. Define __str__(self) to return a human-readable string, which print(object) uses.

Common mistake

Assigning the public property from inside its setter calls the setter again. Write the backing attribute after validation instead. During initialization, assign through the public property so the same validation runs. Raise before storing a rejected value, leaving the previous valid state intact. A string method must return text rather than print it.

Your task

Implement a meter whose readable level survives rejected assignments, including a constructor rejection for a negative starting level.

challenge icon

Challenge

Beginner

Implement Meter(level) with property level, backed by _level. Both construction and later assignment accept nonnegative integers; reject negative values by raising ValueError before changing stored state. Implement __str__ returning level=N. Input is one integer initial level and then a space-separated line of proposed levels. The driver assigns each value, prints ok or invalid, then prints the meter after every attempt. With no attempts it prints the initial meter once. If construction rejects a negative initial level, print only invalid start. Use the same validation during initialization by assigning through the property.

The locked driver reads input and prints results. Submit the required class and function definitions only; do not read input or print in your solution. Keep the API names exactly as specified.

Your code goes in the editable files meter.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable 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 JavaScript Developers

Practice on your own: Online Python compiler