Functions and Objects · Objects · lesson 6 of 10
Classes and instances
about 14 minutes · free · runs in your browser
Step 1 of 2
A template for objects
A class describes a kind of thing; an instance is one of them.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
rex = Dog("Rex", "collie")
rex.name # "Rex"
__init__ runs automatically when you create an instance. It is not a constructor in
the C++ sense — the object already exists — it is where you set the object up.
self is the instance being worked on. It is the first parameter of every method, and
Python passes it for you: you write Dog("Rex", "collie") with two arguments, and
__init__ receives three.
Attributes assigned to self belong to that one instance. Two dogs have two names.
Your turn: write a Book class taking title, author and pages, storing
each on the instance.
You start from this, and edit it in the browser:
class Book:
def __init__(self, title, author, pages):
# Store the three values on self.
pass
Step 2 of 2
Methods
A method is a function that lives on a class and receives the instance as self:
class Counter:
def __init__(self):
self.value = 0
def increment(self, by=1):
self.value += by
return self.value
Inside a method, self.value reads or writes that instance's attribute. Forgetting
self. is the usual early mistake — a bare value = 0 creates a local variable that
disappears the moment the method returns.
Your turn: give Book a reading_time(pages_per_hour=40) method returning how
many hours it would take, rounded to one decimal place.
You start from this, and edit it in the browser:
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def ():