Everything is an object
This module starts the second half of the course, which the MOOC calls the Advanced Course in Programming. Its big idea is object-oriented programming: building programs out of objects that keep data together with the operations on that data. You have been using objects all along without calling them that.
Data that belongs together
When several values describe one thing, you have kept them together in a dictionary (or a tuple): a pet's name, species and age, for example. Here are two pets:
pet1 = {"name": "Biscuit", "species": "cat", "age": 4}
pet2 = {"name": "Pepper", "species": "dog", "age": 2}
pet1["age"] += 1
print(pet1["name"], pet1["age"])
print(pet2["name"], pet2["age"])
Biscuit 5
Pepper 2Each dictionary is an object: a whole of its own in the computer's memory, holding data that belongs together. The two dictionaries have the same keys, but they are separate objects, so changing one doesn't change the other. This is what programmers mean when they say that objects are independent.
Every value is an object
In Python, every value is an object: numbers, strings, lists, dictionaries, even True and None. A variable doesn't hold the object itself but a reference to it, as you saw in the References module, where two variables referred to the same list.
Every object has a type, and the function type tells you which:
>>> type(42)
<class 'int'>
>>> type("Biscuit")
<class 'str'>
>>> type([4, 2])
<class 'list'>
>>> type({"name": "Pepper"})
<class 'dict'>Python calls the type of an object its class. Classes are what this part of the course is about, and soon you'll write your own.
You met two more words in the References module. Lists and dictionaries are mutable: they can be changed after they are made. Numbers, strings and tuples are immutable: they can't. When a program seems to change a string, Python really makes a new string, and the variable then refers to the new one:
word = "cat"
other = word
word = word + "s"
print(word)
print(other)
cats
catThe string "cat" stays as it was, and other still refers to it.
Objects in and out of functions
A function can take objects as its arguments and return one of them: the whole object, with all its data.
def older(pet1, pet2):
if pet1["age"] >= pet2["age"]:
return pet1
return pet2
cat = {"name": "Biscuit", "species": "cat", "age": 4}
dog = {"name": "Pepper", "species": "dog", "age": 2}
winner = older(cat, dog)
print(winner["name"])
print(winner)
Biscuit
{'name': 'Biscuit', 'species': 'cat', 'age': 4}The caller gets the whole dictionary back and can use any of its data, not just the name.