Computed Properties and Text
Lesson 36 of 48 in Coddy's Python for Swift Developers course.
Swift computed properties expose getter/setter behavior behind property syntax. Python property provides a similar public interface through decorated methods. A validating setter can raise ValueError for negative input and store the valid value in an internal attribute. __str__ supplies readable text for print, similar in purpose to CustomStringConvertible.description. Avoid assigning the public property from inside its setter, which would recurse.
Swift example
struct Meter: CustomStringConvertible {
let level: Int
var description: String { "level=\(level)" }
}
print(Meter(level: 3))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")
self._level = value
def __str__(self):
return f"level={self.level}"
print(Meter(3))Porting trap
Python leading underscores are conventions, not Swift private access control. Validation applies through the public property path.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs and Dynamic Attributesinit to __init__self and Method ReferencesType Properties and ShadowingComputed Properties and TextRecap: Model a Bank Account2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler