1. Define a class

A class is a blueprint for creating objects. You define it with class, a name in CapWords (also called PascalCase), a colon and an indented body:

  • class starts the definition; Dog is the name you choose.
  • pass does nothing. It is needed when a block has no statements yet, because a body cannot be empty.
  • The class body runs once, when Python reaches the class statement, not every time you create an object.

Dog() creates an instance of the class: a new object built from that blueprint. The parentheses are required, exactly like a function call.

type(object) returns the class of a value, so type(dog) is Dog. A class also has a __name__ attribute with its name as a string:

isinstance() is a built-in function. Its signature is:

  • object — the value to check.
  • classinfo — a class, or a tuple of classes, to check against.

It returns True when the object was created from that class, and False otherwise:

Coming from JavaScript? A class is close to a JS class, but Dog() does not need new. isinstance(obj, Dog) is obj instanceof Dog.

#01

Define a class and create an instance

Define an empty class named Dog. Its body only needs pass. Create one instance with Dog() and store it in a variable named dog. Print the name of its class with type(dog).__name__.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Check the class with isinstance

Define the empty class Dog and create dog = Dog(). Use isinstance() to check that dog belongs to Dog, and print the boolean result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Compare the instance with another type

Define the empty class Dog and create dog = Dog(). Print the result of checking dog against Dog, then the result of checking it against str. An instance is only an instance of the class that created it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

The class body runs once

A class body may contain any statement. Define a class named Thing whose body only prints Defining Thing. Create two instances, first = Thing() and second = Thing().

Because the body belongs to the class definition, it runs when Python reads the class statement, not when the instances are created. Do not print anything else.

Print exactly:

Create a free account to save your progress and unlock chapter 2.