chapter nine

9 Objects

 

Object-oriented programming has become a mainstream, or even the mainstream, way of approaching programming. The idea is a simple one: Instead of defining our functions in one part of the code, and the data on which those functions operate in a separate part of the code, we define them together.

Or to put it in terms of language: In traditional, "procedural" programming, we write a list of nouns (data) and a separate list of verbs (functions), leaving up to the programmer to figure out which goes with which. In object-oriented programming, the verbs (functions) are defined along with the nouns (data), helping us to know what goes with what.

In the world of object-oriented programming, each noun is an "object." We say that each object has a "type," or a "class," to which it belongs. And the verbs (functions) we can invoke on each object are known as "methods."

For an example of traditional, "procedural" programming vs. object-oriented programming, consider how we could calculate a student’s final grade, based on the average of their test scores. In procedural programming, we would make sure that the grades are in a list of integers, and then write an average function that returns the arithmetic mean:

def average(numbers):
    return sum(numbers) / len(numbers)

scores = [85, 95, 98, 87, 80, 92]
print(f'The final score is is {average(scores)}.')

9.1  Ice cream scoop

9.1.1  Solution

9.1.2  Discussion

9.1.3  Beyond the exercise

9.2  Ice cream bowl

9.2.1  Solution

9.2.2  Discussion

9.2.3  Beyond the exercise

9.3  Bowl limits

9.3.1  Solution

9.3.2  Discussion

9.3.3  Beyond the exercise

9.4  A bigger bowl

9.4.1  Solution

9.4.2  Discussion

9.4.3  Beyond the exercise

9.5  FlexibleDict

9.5.1  Solution

9.5.2  Discussion

9.5.3  Beyond the exercise

9.6  Animals