Menu
CoddyTech

Readers, Writers, and str

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

Ruby attr_reader and explicit writer methods expose controlled access to instance variables. Python property provides getter and optional setter behavior behind attribute syntax. Store a property's backing value under a different name such as _level to avoid recursively calling the property itself. A leading underscore is a convention, not enforced privacy. Ruby to_s and Python __str__ customize readable string conversion. Python __repr__ has a separate debugging role. Route constructor assignment through a property setter when construction must enforce the same validation as later updates. Raise an exception rather than silently accepting an invalid value.

Ruby

class Meter
  attr_reader :level
  def level=(value)
    raise ArgumentError if value < 0
    @level = value
  end
  def initialize(value)
    self.level = value
  end
  def to_s
    "level=#{level}"
  end
end
puts Meter.new(3)

Python

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

Porting trap

Do not call a Python property as if it were an ordinary method. Use meter.level, while a method such as meter.reset() needs parentheses.

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 Ruby Developers

Practice on your own: Online Python compiler