← Python Crash Course

PCC·09 · Chapter record

Classes

Chapter 9 — modeling real things as objects

Done

Five sessions on object-oriented Python: writing a class and making instances from it, default attributes and the three ways to modify them, inheritance, overriding a parent's method, and building classes out of other classes. Each one explains the concept, lists the key terms, then gives you exercises — try them yourself before revealing the code.

9.1

Creating and Using a Class

  • A class is a set of instructions for making an object — by convention its name is capitalized, like Dog.
  • __init__() is a special method Python runs automatically every time you create a new instance — it sets up that instance's starting attributes.
  • The first parameter of every method is self — a reference to the specific instance the method was called on. Python passes it automatically; you never supply it yourself.
  • self.name = name attaches a value to the instance as an attribute — from then on, every method (and you, from outside) can read it as instance.name.
  • Each instance is independent — creating a second Dog doesn't affect the first one's attributes at all.
class
a blueprint for creating objects
instance
one specific object made from a class
__init__()
runs automatically when a new instance is created
self
a reference to the instance a method was called on
attribute
a value attached to an instance via self.name = value
Activity 1

Make a class Restaurant with restaurant_name and cuisine_type attributes, plus a describe_restaurant() method. Create an instance and call the method.

Activity 2

Create three different Restaurant instances and call describe_restaurant() for each — confirm they stay independent.

▶ Dog Kennel