liveBook · Manning

Circle

As explained in Get Programming: Learn to code with Python

Circle is a book-defined Python class whose instances represent circles with a radius data attribute and operations for changing or retrieving that radius.

Circle is a Python class for making circle objects. Each instance starts with a radius data attribute set to 0, and the class provides operations for changing or retrieving that radius. section 31.1 section 31.2

class Circle(object):

The class header names Circle as a new object type. section 31.1

The class demonstrates these connected ideas:

  • __init__ is a special method called when a Circle instance is created. section 31.2
  • self.radius identifies a radius belonging to one particular circle, so different instances can hold different values. section 31.2 section 31.4
  • Dot notation calls operations on an object, such as changing one_circle’s radius or getting its current radius. section 31.4
  • Python can also call a method through the class name by passing the target object explicitly, as in Circle.change_radius(c, 2). section 31.6

Creating and changing two circles

one_circle = Circle()\nanother_circle = Circle()\none_circle.change_radius(4)\nprint(one_circle.get_radius())\nprint(another_circle.get_radius())\n\nThe output is 4 followed by 0: changing one instance does not change the other. section 31.4

Circles inside a Stack

Circle objects can be placed in a Stack. One example adds a circle with radius 2, then creates five separate circles with radius 1. Another adds the same radius-1 circle object five times, illustrating the difference between creating new instances and reusing one instance. section 32.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains class definition, initialization, self, instance state, method calls, and explicit class dispatch, but not advanced class design.
Examples
Uses radius changes, independent circle instances, explicit method calls, and stacks containing separate or repeated Circle objects.
What it assumes
Assumes basic Python assignment and function familiarity while teaching classes, instances, methods, and self from first principles.
What you can do after
Build it from scratch by defining Circle, creating instances, changing or reading radii, and storing circles in a stack.
How it connects
Connects classes with objects, instances, methods, data attributes, dot notation, and stacks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.