LESSON 10 · BEGINNER PATH12 min

Classes and Objects

Create a simple class and give each instance its own data.

Video coming to YouTube

Work through the full lesson and run its code while the video is being prepared for publication.

Understand the concept

A class describes how objects of one kind are built. The __init__ method sets up each new object, and self refers to the particular instance being created or used.

An instance can store data in attributes such as self.title. Methods are functions attached to the class. Calling an instance method passes that instance as self automatically.

  • class defines a type
  • __init__ sets instance attributes
  • self refers to the instance

See it step by step

Read the code, predict the output, then compare it with the result.

01. Build and describe an object

PYTHON
class Dog:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return f"Dog: {self.name}"

pet = Dog("Pip")
print(pet.describe())
EXPECTED OUTPUT
Dog: Pip

__init__ stores the argument on this object. The method reads that stored attribute through self.

02. Keep objects independent

PYTHON
class Counter:
    def __init__(self):
        self.value = 0

first = Counter()
second = Counter()
first.value = 2
print(first.value)
print(second.value)
EXPECTED OUTPUT
2
0

Each new Counter has its own value. Changing first does not change second.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnCreate a second Book named 'Code Journal' with 120 pages and store it in second_book. Print its summary, then print the first book summary again.
Need a hint?

Construct second_book = Book('Code Journal', 120). Call second_book.summary() inside print(), then call first_book.summary() again.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.When is __init__ called?

    02.What does self refer to inside an instance method?

    03.If two Book objects set self.title differently, what does each store?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Omitting self in a method

    COMMON MISTAKE
    class Book:
        def summary():
            return "A book"
    book = Book()
    print(book.summary())
    FIX
    class Book:
        def summary(self):
            return "A book"
    book = Book()
    print(book.summary())

    What happens: TypeError because Python passes the instance automatically.
    Instance methods need self as their first parameter.

    Forgetting self on an attribute

    COMMON MISTAKE
    class Book:
        def __init__(self, title):
            title = title
    book = Book("Python Notes")
    print(book.title)
    FIX
    class Book:
        def __init__(self, title):
            self.title = title
    book = Book("Python Notes")
    print(book.title)

    What happens: AttributeError because no title attribute was stored on the object.
    Assign to self.title to save the value on the instance.