Classes and Objects
About 18 minutes
Why this matters
So far your data and your functions have lived apart. A class bundles them: it describes a kind of thing, with its own data and its own abilities. Each thing made from it is an object (an instance). You have used objects all along: every list, string and dictionary is one.
The idea
class Dog:
def __init__(self, name, age=1): # runs when you create a Dog
self.name = name # attributes: data stored on this object
self.age = age
rex = Dog("Rex", 3) # create an instance
fido = Dog("Fido")
print(rex.name, rex.age) # Rex 3
print(fido.age) # 1
rex.age = 4 # change only Rex
__init__is the constructor; it sets up a new object.selfis the object being created or used. Python passes it in for you, but you must list it first.- Class names use
CamelCase; attributes usesnake_case.
Try it
Create two Dog objects, change one’s age, and print both. Then print type(rex) and isinstance(rex, Dog).
Your turn
Write:
class Pointwith attributesxandy, both defaulting to0.Point()is the origin andPoint(3, 4)hasx == 3.class Book(title, author, pages)with those three attributes, pluspages_readstarting at0andnotesstarting as a new empty list (every book needs its own list).make_library(rows):rowsis a list of(title, author, pages)tuples. Return a list ofBookobjects, one per row, in order.
Recap
- A class describes a kind of object;
ClassName(...)creates an instance. __init__(self, ...)sets up attributes withself.name = value.- Each object keeps its own attribute values.
Common mistakes
- Forgetting
selfin the method definition:TypeError: __init__() takes 1 positional argument but 2 were given. - Writing
x = xinstead ofself.x = x, so nothing is stored (AttributeErrorlater). - A mutable default such as
def __init__(self, notes=[]), which is shared by every object.