After this lesson you can describe your own kind of thing in Python, such as a book in a library, and then create as many of them as you need.
Why classes exist
So far you have used values that Python gave you: numbers, strings, lists and dictionaries. Each of those is a type, and each type knows how to behave. A string knows how to turn itself into upper case. A list knows how to add an item.
A class lets you make a new type. Suppose you are writing a program for a small library. A book has a title, an author and a number of pages, and you might want to describe it in a sentence. You could keep these details in loose variables or dictionaries, but a class keeps the data and the behaviour together in one place.
The vocabulary is simple:
- A class is a blueprint. It describes what a kind of thing looks like and what it can do.
- An object (or instance) is one real thing built from the blueprint.
Think of a class as the printed form and an object as one filled-in form.
Your first class
You define a class with the class keyword, a name and a colon. By convention class names start with a capital letter. The smallest possible class has a body of pass, which means "nothing here yet".
class Book:
pass
print(type(Book))<class 'type'>To build an object, call the class as if it were a function:
first = Book()
second = Book()
print(type(first))
print(first is second)<class '__main__.Book'>
Falsefirst and second are two separate objects made from the same class. The is test confirms that they are not the same object.
Giving an object data
An object can carry named pieces of data called attributes. You create one by assigning to a name after a dot:
first.title = "The Silent Garden"
first.pages = 320
second.title = "Night Trains"
second.pages = 180
print(first.title, first.pages)
print(second.title, second.pages)The Silent Garden 320
Night Trains 180Each object keeps its own values. Changing first.pages leaves second.pages alone. You will see a tidier way to set attributes when the object is created in the next lesson. For now the important idea is that data lives on the object and you reach it with a dot.
Asking for an attribute that was never set is an error:
print(first.author)AttributeError: 'Book' object has no attribute 'author'Giving an object behaviour
A function written inside a class is called a method. The first parameter of a method is always the object it was called on, and by convention it is named self. Python fills it in for you.
class Book:
def describe(self):
return f"{self.title} has {self.pages} pages"
novel = Book()
novel.title = "The Silent Garden"
novel.pages = 320
print(novel.describe())The Silent Garden has 320 pagesWhen you write novel.describe(), Python quietly passes novel as self. Inside the method, self.title therefore means "the title of whichever book this was called on". Make a second book and the same method describes that one instead:
short = Book()
short.title = "Night Trains"
short.pages = 180
for book in [novel, short]:
print(book.describe())The Silent Garden has 320 pages
Night Trains has 180 pagesChecking what an object is
type() tells you the exact class of an object, and isinstance() answers a yes or no question about it:
print(type(novel))
print(isinstance(novel, Book))
print(isinstance(novel, str))<class '__main__.Book'>
True
FalseThe first line shows __main__ because the class was defined in the script you are running. In a program split across files, you would see the module name there instead.
Everything in Python is an object, including numbers and strings. "hello".upper() is a method call on a string object, exactly like novel.describe().
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Forgetting the parentheses.
book = Bookdoes not create an object. It gives the class a second name. You needBook(). - Leaving out
self. A method written asdef describe():fails when called on an object, because Python still passes the object in as the first argument. - Writing
self.titleoutside a method.selfonly exists inside methods. Outside, use the name of your object, such asnovel.title. - Mixing up the class and the object.
Book.pages = 100changes the blueprint, whilenovel.pages = 100changes one book. Beginners often set attributes on the class by accident. - Reading an attribute that was never set. This raises
AttributeError. The next lesson shows how to make sure every object starts with all of its attributes.
Exercise
Create a class called Student. Make two students, give each a name and a grade (a number), and add a method called report that returns a sentence such as Asha scored 82. Print the report for both students.
Show one possible answer
class Student:
def report(self):
return f"{self.name} scored {self.grade}"
a = Student()
a.name = "Asha"
a.grade = 82
b = Student()
b.name = "Ben"
b.grade = 74
print(a.report())
print(b.report())Asha scored 82
Ben scored 74Key points
- A class is a blueprint, and an object (also called an instance) is one thing built from that blueprint.
- You create an object by calling the class like a function, for example Book().
- Data stored on an object is called an attribute, and a function defined inside a class is called a method.
- Every object has its own attributes, so changing one book does not change another.
- type() and isinstance() tell you which class an object belongs to.