Properties and Object Text
Lesson 36 of 48 in Coddy's Python for PHP Developers course.
PHP commonly exposes methods for validated state and uses __toString for object text. Python @property lets a getter run on attribute access; a matching setter validates assignment while storing a backing attribute such as _level. An underscore is a convention, not PHP private visibility. Python __str__ defines the readable text used by str and print. The property setter should validate before replacing old state.
PHP 8.3
<?php
class Meter {
private $level;
public function __construct($level) { $this->level = $level; }
public function __toString(): string { return 'level=' . $this->level; }
}
echo new Meter(3), "\n";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
A Python property is used as an attribute, without parentheses. Writing self.level = value inside its own setter would recurse; write to the backing attribute instead.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking7Instances and Shared State
Instances Without newConstructors and Fresh ListsThis and Bound MethodsStatic and Instance AttributesProperties and Object TextRecap: Model a Bank Account2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler