Properties and Object Text
Lesson 36 of 48 in Coddy's Python for C++ Developers course.
A Python property intercepts attribute reads and writes through getter and setter functions. Use @property and @level.setter, storing the value in _level. A leading underscore is a convention, not C++ private access control. Validate before assigning backing state so a rejected update leaves the old value intact. __str__ returns a string used by str(obj) and print(obj); it fills a role often handled by C++ stream insertion overloads.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Meter {
int level;
explicit Meter(int value) : level(value) {
if (value < 0) throw std::invalid_argument("negative");
}
};
Meter meter(3);
std::cout << "level=" << meter.level << '\n';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
Inside the setter, assigning self.level would call the setter again. Assign self._level after validation instead.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and 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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Instances Without newInitialization and Ownershipthis and Bound MethodsShared and Instance StateProperties and Object TextRecap: Model a Bank Account2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler