Property Accessors and Text
Lesson 36 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin properties can have custom getters and setters plus a backing field. Python @property similarly mediates attribute access, while a conventionally named _level can hold state. A Python underscore is not Kotlin private visibility. Kotlin toString corresponds in purpose to Python __str__. The setter should validate before changing state so rejected updates preserve the previous value.
Kotlin
class Meter(private val level: Int) {
override fun toString() = "level=$level"
}
fun main() { println(Meter(3)) }Python
class Meter:
def __init__(self, level):
self._level = level
@property
def level(self):
return self._level
def __str__(self):
return f"level={self.level}"
print(Meter(3))Porting trap
Inside a Python setter, assign the backing attribute rather than the property itself or the setter recurses. Access a property without method-call parentheses.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking7Instances and Shared State
Classes and Attribute AccessConstructors and Fresh StateReceivers and Bound MethodsCompanions and Class StateProperty Accessors and TextRecap: Model a Bank Account2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler