Properties and Access Control
Lesson 36 of 48 in Coddy's Python for Java Developers course.
Offer attribute-style access while preserving validation with property. Java normally exposes getLevel/setLevel methods around a private field. Python level assignment can invoke a setter, which checks the value before storing it in _level. Initializing through the same property reuses that rule. __str__ returns human-readable text, serving a role similar to Java toString. It must return str rather than print. Keep backing storage distinct from the property name to avoid recursive setter calls.
Java excerpt: class member declarations
// Class member
static class Meter {
private int level;
void setLevel(int value) {
if (value < 0) throw new IllegalArgumentException();
level = value;
}
int getLevel() { return level; }
}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))Watch the difference
A single underscore marks an internal name by convention; it is not Java private access enforcement. A double-leading underscore uses name mangling to reduce accidental subclass collisions, not security or inaccessible storage.
Practice
Apply this comparison in the task below. 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.
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. This is a Python property API, not Java get/set method calls.
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 Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking7Instance and Class State
Instances Without newInitializing Instance StateBound Methods and selfClass State Is Not a FieldProperties and Access ControlRecap: Account State2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler