liveBook · Manning

Class

As explained in Python Workout: 50 ten-minute exercises

A class is a programming-language construct that defines a type’s structure or behavior and provides a basis for creating or representing objects.

A class defines one kind of object and its behavior. Treat it as a factory: calling Scoop('chocolate') creates an instance whose flavor attribute stores 'chocolate'. section 9.1

Define a class with the class keyword. Its __init__ method receives the new instance as self and assigns instance attributes such as self.flavor = flavor. Python convention requires self as the first method parameter, although the name is not enforced. section 9.2

Create and inspect several instances

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) Each instance has the same class-defined structure but its own flavor value. The list and loop make the relationship between a class, its instances, and their attributes concrete. section 9.1

Classes can organize larger systems through methods, attributes, composition, and inheritance. A zoo model can use animal classes, cages containing animals, and a Zoo class that searches animals by color or number of legs. Inheritance can reuse behavior, but its hierarchy should be chosen deliberately. section 9.26 section 9.38

Calling Foo(10) invokes the class as a callable: __new__ creates the object, then __init__ initializes it. Most classes only need __init__, while __new__ is rarely redefined. section 9.5

class Zoo():
    def __init__(self):
        self.cages = []                               #1

    def add_cages(self, *cages):
        for one_cage in cages:
            self.cages.append(one_cage)
 
    def __repr__(self):
        return '\n'.join(str(one_cage)
                         for one_cage in self.cages)
 
    def animals_by_color(self, color):                #2
        return [one_animal
                for one_cage in self.cages
                for one_animal in one_cage.animals
                if one_animal.color == color]
 
    def animals_by_legs(self, number_of_legs):        #3
        return [one_animal
                for one_cage in self.cages
                for one_animal in one_cage.animals
                if one_animal.number_of_legs ==
                        number_of_legs]
 
    def number_of_legs(self):                         #4
        return sum(one_animal.number_of_legs
                   for one_cage in self.cages
                   for one_animal in one_cage.animals)
 
wolf = Wolf('black')
sheep = Sheep('white')
snake = Snake('brown')
parrot = Parrot('green')
 
print(wolf)
print(sheep)
print(snake)
print(parrot)
 
c1 = Cage(1)
c1.add_animals(wolf, sheep)
 
c2 = Cage(2)
c2.add_animals(snake, parrot)
 
z = Zoo()
z.add_cages(c1, c2)
 
print(z)
print(z.animals_by_color('white'))
print(z.animals_by_legs(4))
print(z.number_of_legs())

Trace a complete Zoo class that stores cages, represents them, and filters nested animals by attributes. section 9.38

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains definitions, instances, attributes, self, initialization, composition, inheritance, and the __new__ to __init__ creation sequence.
Examples
Demonstrates ice-cream scoops, zoo animals and cages, beverage defaults, files, phones, bread, and inheritance hierarchies.
What it assumes
Assumes Python functions and basic data structures while teaching class syntax, instance attributes, self, and object construction.
What you can do after
Build classes with initialized attributes, instantiate them, call methods, compose objects, and extend behavior through inheritance.
How it connects
Connects classes with objects, instances, attributes, methods, composition, inheritance, and object creation.

Also explained in

Compare how 21 books explain class →

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.