EE1021 Programming for Engineers · Lecture 7 Lab · 2026–2027
By the end of the lab, you should be able to:
self__str__ to return a useful representationFor every task:
self refers to.Open starter/lecture7_lab.py and keep the supplied public method names unchanged.
Why could two Sensor instances unexpectedly contain the same readings?
readings is attached to the class and refers to one shared list. Create self.readings = [] inside __init__.
__init__The constructor receives:
sensor_id, a non-empty string;unit, a non-empty string.It must create three instance attributes:
Create a new empty readings list for every instance.
Verify:
t1.readings is not p1.readings.Record the expected state before running.
Explain:
self in each constructor call;self.sensor_id = sensor_id is not circular;__init__.add_readingContract:
Raise TypeError("reading must be numeric") for a nonnumeric value.
Test the method on both objects and verify that only the receiver changes.
Complete:
| call | receiver passed as self |
affected list |
|---|
The receivers are t1, p1, and t1; the final lists are [20.0, 22.0] and [100.0].
Implement:
reading_count returns an integer.latest returns the final reading.average returns the arithmetic mean.latest and average raise ValueError("sensor has no readings") when empty.Classify each method:
add_readingreading_countlatestaverageadd_reading is a command that changes state. The other three are queries that return information.
statusRules:
low → "low";high → "high";"normal";low > high raises ValueError("low must not exceed high").Reuse latest() rather than indexing the list again.
For limits low=20 and high=30, predict the status of:
Low, normal, normal, normal, high.
__str__Required format:
The method must return a string. It must not print.
Verify both:
What happens if __str__ prints the ID but returns nothing?
The method implicitly returns None, so str() and print(object) cannot obtain the required string and Python raises TypeError.
Implement the supplied standalone function:
Return:
description;count;latest;average;status.Use the object’s methods instead of duplicating formulas.
The starter folder includes starter/sensor_test_data.txt.
Each valid line has:
Optional extension: parse the file, build one Sensor object per ID, and add each reading to the appropriate object.
Reuse Lecture 5 dictionaries and Lecture 6 parsing principles.
Your tests must cover:
latest and average calls;__str__ result.Choose one completed method and explain:
self;Each student independently completes one action:
self through two method calls;__str__;One retry is available after focused feedback.
__str__ returns the required string.self refers to.