liveBook · Manning

Scoop

As explained in Python Workout: 50 ten-minute exercises

Scoop is a book-specific Python object type representing an individual scoop that can be placed in a Bowl.

Model one ice-cream scoop as a Python object with a single flavor attribute. Define Scoop as a class, then create instances by passing each flavor to Scoop(). section 9.1 section 9.2

Implement Scoop by following these steps:

  • Define the class with the class keyword. section 9.2
  • Use __init__(self, flavor) to assign self.flavor = flavor on each new instance. section 9.2
  • Create multiple Scoop objects and store them in a list, preserving each object's flavor attribute. section 9.1 section 9.7
  • Use self as the conventional first method parameter; Python does not reserve that name, but developers and tools expect it. section 9.2

Create and collect scoops

class Scoop: def __init__(self, flavor): self.flavor = flavor scoops = [Scoop(flavor) for flavor in ('chocolate', 'vanilla', 'persimmon')] for scoop in scoops: print(scoop.flavor) section 9.1 section 9.2

Figure 9.1 Three instances of Scoop, each referring to its class

Visualize three Scoop instances and their relationship to the Scoop class. section 9.1

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains class creation, initialization, self, attributes, and list storage, while deferring strict type enforcement.
Examples
Uses chocolate, vanilla, and persimmon scoops collected in a list and later stored in a Bowl.
What it assumes
Assumes familiarity with Python functions while teaching classes, instances, attributes, and self through the implementation.
What you can do after
Build it from scratch by defining Scoop, creating flavored instances, collecting them, and reading their attributes.
How it connects
Connects classes, objects, instances, attributes, __init__, lists, and Bowl.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.