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
class Dog:
def __init__(self, name):
self.name = name
def describe(self):
return f"Dog: {self.name}"
pet = Dog("Pip")
print(pet.describe())Dog: Pip__init__ stores the argument on this object. The method reads that stored attribute through self.
02. Keep objects independent
class Counter:
def __init__(self):
self.value = 0
first = Counter()
second = Counter()
first.value = 2
print(first.value)
print(second.value)2
0Each 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 runNeed input()? Add one value per line
Your output appears here.
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.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Omitting self in a method
class Book:
def summary():
return "A book"
book = Book()
print(book.summary())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
class Book:
def __init__(self, title):
title = title
book = Book("Python Notes")
print(book.title)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.