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)}.')

Exercise 38 Ice cream scoop

 
 

Working it out

 

Solution

 
 
 
 

Screencast solution

 
 
 

Beyond the exercise

 
 
 

Exercise 39 Ice cream bowl

 
 

Working it out

 

Solution

 
 
 

Screencast solution

 

Beyond the exercise

 
 
 

Exercise 40 Bowl limits

 
 

Working it out

 
 

Solution

 
 

Screencast solution

 
 

Beyond the exercise

 
 
 

Exercise 41 A bigger bowl

 
 

Working it out

 
 

Solution

 
 
 
 

Screencast solution

 
 
 

Beyond the exercise

 
 

Exercise 42 FlexibleDict

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest