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 it 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 versus 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’d make sure the grades were in a list of integers and then write an average function that returned the arithmetic mean:

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

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

9.1 Exercise 38 ■ Ice cream scoop

9.1.1 Working it out

9.1.2 Solution

9.1.3 Beyond the exercise

9.2 Exercise 39 ■ Ice cream bowl

9.2.1 Working it out

9.2.2 Solution

9.2.3 Beyond the exercise

9.3 Exercise 40 ■ Bowl limits

9.3.1 Working it out

9.3.2 Solution

9.3.3 Beyond the exercise

9.4 Exercise 41 ■ A bigger bowl

9.4.1 Working it out

9.4.2 Solution

9.4.3 Beyond the exercise

9.5 Exercise 42 ■ FlexibleDict

9.5.1 Working it out

9.5.2 Solution

9.5.3 Beyond the exercise

9.6 Exercise 43 ■ Animals

9.6.1 Working it out

9.6.2 Solution

9.9 Summary