A Class of Your Own: the Flashcard

So far every value in your programs has been of a kind Python already knows: a number, a string, a list, a dictionary. A class lets you describe a new kind of value of your own. You decide what data each value of that kind holds and what it can do. Then you can make as many of them as you need, and each one looks after its own data.

A class describes one kind of value

Think of a rectangle. Every rectangle has a width and a height, and every rectangle has an area you can work out from them. Those two facts describe what a rectangle is. A class is exactly that kind of description, written in Python: the parts every value of the kind has, and the things it can do.

A class on its own is only the description. To get a real rectangle you call the class, with round brackets, the same way you call a function. Each call gives back a new, separate value made from the description. Python calls such a value an object, or an instance of the class. One class, many objects: a rectangle 3 by 4 and a rectangle 10 by 20 are two objects of the same class.

Here is the smallest useful version of that class. The next sections explain every line of it.

A class and two objects made from it
class Rectangle:
    def __init__(self, width: int, height: int) -> None:
        self.width = width
        self.height = height

    def area(self) -> int:
        return self.width * self.height


small = Rectangle(3, 4)
big = Rectangle(10, 20)

The line class Rectangle: starts the description, and everything indented under it belongs to the class, just as an indented block belongs to an if or a def. Class names are written with a capital letter at the start of each word, like Rectangle or ShoppingList: that is the convention of the Python style guide, and it lets a reader tell a class from a function at a glance.

Defining the class makes no rectangle yet. The two lines at the bottom do: each call to Rectangle(...) builds one new object, and the assignment gives it a name.

  • class Rectangle
    • width
    • height
    • area()
  • small
    • width = 3
    • height = 4
  • big
    • width = 10
    • height = 20
  • class Rectangle to small: Rectangle(3, 4)
  • class Rectangle to big: Rectangle(10, 20)

True or false?

After `small = Rectangle(3, 4)` and `big = Rectangle(10, 20)`, changing the width of `small` also changes the width of `big`.

False. Each call to the class makes a separate object with its own data. Changing one object leaves the other as it was.

Writing the `class Rectangle:` block on its own creates no rectangle object.

True. The class is only the description. An object exists once the class is called, as in `Rectangle(3, 4)`.

__init__ fills a new object with its data

Inside the class there are two def blocks. A function written inside a class is called a method. One of them has a special name with two underscores on each side: __init__ (say it "dunder init", short for "double underscore init").

You never call __init__ yourself. When you call the class, Python first makes a new, empty object, then runs __init__ on it at once, and finally hands the object back to you. The arguments you put in the call are passed on to __init__. So Rectangle(3, 4) runs __init__ with width set to 3 and height set to 4.

  • Rectangle(3, 4) you call the class
  • New empty object Python makes it
  • __init__ runs self.width = 3, self.height = 4
  • Object handed back small = ...
  • Rectangle(3, 4) to New empty object
  • New empty object to __init__ runs
  • __init__ runs to Object handed back

The first parameter of __init__, self, is the new object itself. The line self.width = width stores the value of the parameter width on that object, under the name width. A value stored on an object like this is called an attribute. You need not list the attributes anywhere first: an attribute comes into existence the moment a value is assigned to it, just as a variable does.

The parameters width and height are local names of __init__ and disappear when it ends. The attributes stay, because they belong to the object, and the object lives on after the call. That is the whole job of __init__: to copy the data the object needs onto the object. It gives nothing back with return, which is why its type hint says -> None.

To read an attribute, write the object, a dot and the attribute's name:

print(small.width)   # 3
print(big.width)     # 10
print(big.height)    # 20

The same name, width, gives a different value for each object, because each object carries its own. You can also assign to an attribute with the same dot, small.width = 5, and only small changes. Asking an object for an attribute it was never given, such as small.colour, stops the program with an AttributeError.

True or false?

`__init__` runs by itself every time the class is called, so the program never writes `__init__(...)` to make an object.

True. Calling the class, as in `Rectangle(3, 4)`, makes the object and runs `__init__` on it, passing on the arguments of the call.

Inside `__init__`, the line `width = width` would store the width on the object just as well as `self.width = width`.

False. Without `self.` the name is only a local variable of `__init__`, gone when the method ends. Only a name written after `self.` becomes an attribute of the object.

Methods, and what self refers to

The second method, area, is an ordinary function with one difference: it lives inside the class, and it is called on one object, with a dot. The object goes before the dot, the method name and its brackets after it:

print(small.area())   # 12
print(big.area())     # 200

The same method gives a different result for each object, because it works with the data of the object it was called on. How does area know which object that is? Python passes it in.

When you write small.area(), Python calls the function area of the class and gives it small as its first argument. That first parameter is named self. So inside the method self refers to small, and self.width * self.height reads the width and height of small. In the call big.area(), the same line reads them from big.

What self refers to in each call
The call you writeWhat Python runsself isResult
small.area()Rectangle.area(small)small12
big.area()Rectangle.area(big)big200

The object before the dot is always the first argument, and Python fills it in for you. So a call always passes one argument fewer than the definition lists: self is the one Python supplies. That is why area, defined as def area(self), is called with empty brackets. It is also why __init__(self, width, height) is reached by a call with two arguments, Rectangle(3, 4).

A method can have parameters of its own after self. One defined as def scale(self, factor) would be called as small.scale(2). Inside it, self is small and factor is 2.

The name self is a convention, not a word Python treats specially. Any name in first place would receive the object. Python programmers use self everywhere, and the style guide asks for it, so that a line like self.width tells any reader at once: this is data of the object the method was called on.

True or false?

To call `area`, defined as `def area(self)`, you write `small.area(small)` so that the method receives the object.

False. Python passes the object before the dot as `self` by itself. The call is `small.area()`, and adding `small` again would be one argument too many.

In the call `big.area()`, the name `self` inside `area` refers to `big`.

True. `self` is whichever object the method was called on. The same method body reads `small` in one call and `big` in the next.

`self` is a reserved word of Python, so the first parameter of a method must have exactly that name.

False. It is only a convention. Python gives the object to the first parameter whatever it is called, but every Python programmer expects `self`.

When a class fits better than a dictionary

A dictionary can hold a rectangle's data too, and a separate function can work out its area. Placed side by side, the two ways look like this:

A dictionary and a function
def area(rect: dict) -> int:
    return rect["width"] * rect["height"]


small = {"width": 3, "height": 4}
print(area(small))   # 12
A class
class Rectangle:
    def __init__(self, width: int, height: int) -> None:
        self.width = width
        self.height = height

    def area(self) -> int:
        return self.width * self.height


small = Rectangle(3, 4)
print(small.area())   # 12

Both print the same number. The difference shows when a program grows.

A dictionary accepts any keys. A dictionary with a key mistyped as "widht", or with a key missing, is still a dictionary. Nothing goes wrong when it is made, so the mistake only surfaces later, far from where it was made.

A class names its parts once, in __init__, so every object made from it is built the same way. A call that leaves out a part stops with an error at the call itself, right where the mistake is.

The behaviour also travels with the data. Anyone holding a rectangle can call area() on it, without hunting for the function that goes with it.

A class fits best when a value has a fixed set of parts and comes with things to do with them. A dictionary stays the better choice when the keys vary from one record to the next or are not known in advance, such as the scores of whichever players happen to take part, or data read from a file whose fields you only pass along.

Every value is an object

The dot in small.area() should look familiar. You have used it all along: name.strip(), words.append("hi"), path.read_text(encoding="utf-8"). That is no coincidence. In Python every value is an object, and every object has a class.

Strings are objects of the class str, lists of list, dictionaries of dict, and a path is an object of a class from the pathlib module. Their methods are defined inside those classes, which come with Python, exactly the way area is defined inside Rectangle.

The built-in function type tells you the class of any value:

print(type("Paris"))             # <class 'str'>
print(type([1, 2, 3]))           # <class 'list'>
print(type({"width": 3}))        # <class 'dict'>
print(type(Rectangle(3, 4)))     # <class '__main__.Rectangle'>

For a class defined in the file you run, Python puts __main__, its name for that file, before the class name.

For a path, type(Path("notes.txt")) names PosixPath on Linux and macOS, or WindowsPath on Windows: calling Path makes an object of the path class that suits the system.

So " Paris ".strip() works just like small.area(): the string before the dot is passed to the method as its self, and the method works on that string's own text. Calling a class to make an object is familiar too: Path("notes.txt") calls the class Path, as Rectangle(3, 4) calls Rectangle. A class you write joins the same system as the values Python provides.

One dot, many classes
A valueIts classA method call on it
" Paris "str" Paris ".strip()
[1, 2, 3]list[1, 2, 3].append(4)
{"width": 3}dict{"width": 3}.keys()
Path("notes.txt")PosixPath or WindowsPathPath("notes.txt").read_text(encoding="utf-8")
Rectangle(3, 4)RectangleRectangle(3, 4).area()

True or false?

Methods called with a dot are a feature only of classes you write yourself.

False. Strings, lists, dictionaries and paths are objects of classes that come with Python, and `strip`, `append` and `read_text` are methods defined in those classes.

In `" Paris ".strip()`, the string `" Paris "` is the object the method works on, just as `small` is in `small.area()`.

True. The object before the dot is handed to the method as its first argument, whether its class comes with Python or was written by you.