Properties and Display Hooks
Lesson 36 of 48 in Coddy's Python for Go Developers course.
Go commonly exposes accessor methods around an unexported field. Python property lets attribute syntax run getter and setter methods. The setter validates before replacing stored state. A leading underscore communicates internal use, but does not enforce Go package-level access control. Python __str__ supplies readable text for print, like Go String() can satisfy fmt.Stringer.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
type Meter struct { level int }
func (m *Meter) SetLevel(n int) error { if n < 0 { return fmt.Errorf("negative") }; m.level = n; return nil }
func (m Meter) Level() int { return m.level }
func (m Meter) String() string { return fmt.Sprintf("level=%d", m.level) }
// Inside main:
m := Meter{}
m.SetLevel(4)
fmt.Println(m.Level())
fmt.Println(m)Python
class Meter:
def __init__(self):
self._level = 0
@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}"
m = Meter()
m.level = 4
print(m.level)
print(m)Porting trap
Inside a property setter, assign self._level, not self.level, or you recursively call the setter. Raising ValueError before assignment leaves the old state intact.
Challenge
BeginnerImplement Meter(level) with a level property backed by _level. Construction and later assignment accept nonnegative integers; negative values raise ValueError without changing state. Initialize through the property. __str__ returns level=N. The driver reads initial level and proposed integer levels, prints ok or invalid then the meter after each attempt, or prints the initial meter once if there are no attempts. Rejected construction prints only invalid start. Go would normally expose accessor methods; this Python contract uses property assignment with validation.
Editable files: meter.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking7Structs to Python Classes
From Structs to InstancesInitialization and Fresh StateReceivers and Bound MethodsClass State and ShadowingProperties and Display HooksRecap: Account State2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler