Your objects in functions and lists
Objects of your own classes are values like any others. Functions can take them as arguments and return them, and lists can hold them.
Functions that make and change objects
A function can create a new object and return it, and a function can change an object it is given:
class Hike:
def __init__(self, name, km, climb):
self.name = name
self.km = km
self.climb = climb
def short_version(hike):
return Hike(hike.name + " (short)", hike.km / 2, hike.climb / 2)
def add_detour(hike, km):
hike.km += km
ridge = Hike("Ridge Loop", 12, 600)
easy = short_version(ridge)
add_detour(ridge, 3)
print(ridge.name, ridge.km)
print(easy.name, easy.km)
Ridge Loop 15
Ridge Loop (short) 6.0add_detour gets a reference to the same object that ridge refers to, so the change is still there after the function ends, just as with a list passed to a function. short_version makes a new, separate object, so the detour added to ridge afterwards doesn't change easy.
Lists of objects
A list of objects works like any list. Loop through it and use each object's attributes:
class Hike:
def __init__(self, name, km, climb):
self.name = name
self.km = km
self.climb = climb
def hikes_up_to(hikes, max_km):
found = []
for hike in hikes:
if hike.km <= max_km:
found.append(hike)
return found
hikes = [Hike("Ridge Loop", 12, 600), Hike("Lake Path", 5, 40), Hike("Old Mill", 8, 150)]
for hike in hikes_up_to(hikes, 8):
print(f"{hike.name}: {hike.km} km")
total = 0
for hike in hikes:
total += hike.climb
print("Total climb:", total, "m")
Lake Path: 5 km
Old Mill: 8 km
Total climb: 790 mhikes_up_to returns a new list, but the objects in it are the same Hike objects as in the original list, not copies.
Printing an object
What about print(hike)? For an object of your own class, Python doesn't know what to show, so it prints the class's name and the object's address in memory, something like this:
<__main__.Hike object at 0x7f2b5c3e1a90>
The address changes from run to run, so for now, print the attributes you want to see. A later module shows how to teach a class to print itself nicely.