Validated Attribute Access
Lesson 36 of 48 in Coddy's Python for R Developers course.
Python properties place getter and setter behavior behind dotted attribute access. R reference-class active bindings and replacement-function patterns can express related ideas, but ordinary list extraction does not automatically validate. Store a Python property's backing value under a separate name to avoid recursively calling its setter. A leading underscore is a convention, not privacy enforcement. Python __str__ controls readable conversion; R often defines a print method that writes output and returns invisibly. Keep these roles distinct: Python __str__ must return a string, not print it. Constructor assignment can reuse a property setter for validation.
R
make_meter <- function(level) {
if (level < 0) stop("negative")
structure(list(level=level), class="meter")
}
format.meter <- function(x, ...) paste0("level=", x$level)
cat(format(make_meter(3)), "\n", sep="")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
A Python property is read with attribute syntax, not parentheses. Its getter may execute code even though the access looks like a field read.
Challenge
BeginnerImplement 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking7Objects and Shared State
R Objects and Python ClassesInitializing Instance StateReceiver Methods and GenericsClass Lookup and Shared ListsValidated Attribute AccessRecap: Model a Bank Account2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler