Classes and Objects

A class lets you create your own type of object. It is useful when some pieces of data, and the code that works on them, belong together under one name.

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

dune = Book("Dune", 412)
sula = Book("Sula", 192)

print(dune.title)
print(sula.pages)

Output:

Dune
192

When you call Book(...), Python creates a new object. Then it runs __init__, a setup function that Python calls for every new object. The new object is passed in as self. A line such as self.title = title stores a value on the object. A value stored this way is called an attribute.

Each object keeps its own attribute values. dune and sula are both books, but they have different titles and page counts. A variable still holds a reference to an object, just like with lists. So other = dune does not copy the book. It gives the same object a second name.

In the exercise, complete __init__ so each employee stores its name and age.