A Python class defines an object type: the properties its objects have and the operations they can perform. Before writing one, ask two questions: What information must each object hold? What should it be able to do? A class lets you give those answers once, then create multiple objects of the same type. section 31.0 section 32.0
class Circle(object):
def __init__(self):
self.radius = 0
In `class Circle(object):`, `class` starts the definition and `Circle` names the new type. `__init__` runs when a Circle is created. Its `self.radius = 0` gives that particular circle a radius of zero. section 31.1 section 31.2
A function defined inside a class is called a method. Methods define operations on its objects. The name `self` refers to the object a method is working on; writing `self.radius` makes `radius` an attribute of that object. A class definition describes the type, but it does not yet create a particular circle. section 31.2
Two circles, two radii
Create two objects with `one_circle = Circle()` and `another_circle = Circle()`. Each is an instance—a specific Circle object. Calling `one_circle.change_radius(4)` changes only the first circle. Their radius-reading methods then produce `4` and `0`. In a call written with dot notation, Python supplies the object before the dot as `self`. section 31.4 section 31.6
Listing 31.1. A Rectangle class
class Rectangle(object):
""" a rectangle object with a length and a width """
def __init__(self, length, width):
self.length = length
self.width = width
def set_length(self, length):
self.length = length
def set_width(self, width):
self.width = width
A Rectangle can instead require `length` and `width` when it is created. In `__init__`, the incoming parameters are temporary; `self.length` and `self.width` remain attributes of the instance. Creating a Rectangle with only one value raises a missing-argument error. section 31.5
Classes become especially useful when an object needs several related operations. A Stack can keep a list as its attribute and offer methods for adding, removing, counting, and showing items. Someone using the Stack can call those methods without managing the underlying list’s rules themselves. Classes can also divide a larger program into parts, such as players and a card deck in a game. section 32.1 section 34.0 section 34.6
Not every value needs its own class. Choose one when its named properties and operations make the program clearer. For practice, design a Queue: decide what holds its items, initialize it, add methods to add and remove items, then create two queues and try the operations. section 33.4 section 32.3




















