Methods and Objects in Action
In the first part you built a class. Now objects do something: they calculate with their values, introduce themselves readably, work in loops and make decisions.
Module 1 — Methods That Calculate
An object can work with its own values.
A list as an attribute
An attribute may also be a list — for example all readings of an experiment. A method can calculate something from it, such as the mean with sum() and len().
class Messreihe:
def __init__(self, name, messwerte):
self.name = name
self.messwerte = list(messwerte)
def mittelwert(self):
return sum(self.messwerte) / len(self.messwerte)
list(messwerte) creates its own copy of the list. If someone changes the original list later, the object is unaffected.
Example 1.1 — Mean of a measurement series
Loading Python…Tests
Module 2 — Objects Introduce Themselves: __str__
What print() does with an object.
Without __str__ shows print only an address
If you print an object with print() , something like <__main__.Messreihe object at 0x…>appears. That helps nobody. With the method __str__ you decide yourself which text should appear — it returns a string, usually built from an f-string.
def __str__(self):
return f"Messreihe {self.name}: {len(self.messwerte)} Werte"
After that, print(druck) shows exactly this text. And str(druck) returns it too.
Example 2.1 — Before and after
Loading Python…Tests
Module 3 — Objects in Loops
Calling the same method many times.
Repeat and collect
An object can be used in a loop as often as you like. A typical pattern is an Rechargeable battery: a variable that counts or sums up, and a list that collects intermediate results.
summe = 0
ergebnisse = []
for nummer in range(1, 4):
summe += w.wuerfeln()
ergebnisse.append(summe / nummer)
After each pass, ergebnisse holds the mean of all rolls so far — the running mean.
Example 3.1 — Running mean
Loading Python…Tests
Module 4 — Methods That Decide
A method can return True or False.
A truth value as the result
A comparison such as 0 <= wert <= 10 yields True or False. If a method returns such a comparison, you can use it directly in a condition: if sensor.ist_plausibel(wert):
def ist_plausibel(self, wert):
return self.minimum <= wert <= self.maximum
PracticeNow Program It Yourself
Four exercises: a measurement series with mean, plus __str__, then the dice simulation with running mean and finally a pressure sensor that checks readings.
Example 4.1 — A method as a condition
Loading Python…Tests
Sources and Further Reading
Module sources and further Python references.
Teaching Material and Documentation
- Lecture notebook IngInfo_WS26_27_VÜ.ipynb, section on object-oriented programming.
- Python tutorial — Classes.
- Real Python — Object-Oriented Programming in Python.
- Theis, Thomas: Getting started with Python. 7th edition, Rheinwerk Verlag, 2023.