Defining a Class

Defining a Class

A class defines a new type of value: what data each one carries, and later, what it can do. An object is one value of that type.

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

class Book: starts the definition. __init__ is a special function that runs when a new Book is created; its job is to store the object's data. self is the object being created, and self.title = title stores the title argument on it. Values stored on self are the object's attributes.

Calling the class like a function creates an object. The arguments go to __init__self is filled in automatically:

book = Book("Emma", "Austen")
print(book.title)
print(book.author)

Output:

Emma
Austen

Each object has its own attributes:

other = Book("Dracula", "Stoker")
print(other.title)
print(book.title)

Output:

Dracula
Emma

A class earns its place when data belongs together — a title without its author is half a book. The dictionaries section handled this with {"title": ..., "author": ...}; a class gives the grouping a name and, in the next lesson, behavior.

Exercise

  1. Define a class named Movie.
  2. Its __init__ takes title, year, and runtime (minutes), and stores all three as attributes with those names.

Movie("Alien", 1979, 117).year is 1979.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestMovie(unittest.TestCase):
    def test_attributes_are_stored(self):
        movie = Movie("Alien", 1979, 117)
        self.assertEqual(movie.title, "Alien")
        self.assertEqual(movie.year, 1979)
        self.assertEqual(movie.runtime, 117)

    def test_each_movie_has_its_own_attributes(self):
        first = Movie("Alien", 1979, 117)
        second = Movie("Arrival", 2016, 116)
        self.assertEqual(first.title, "Alien")
        self.assertEqual(second.title, "Arrival")
class Movie:
    def __init__(self, title, year, runtime):
        self.title = title
        self.year = year
        self.runtime = runtime


movie = Movie("Alien", 1979, 117)
print(movie.title)
print(movie.year)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.