Using Class Constructors

Using a class is like using a cookie recipe. Sometimes you want your instance – the cookie – to be setup in a certain way, such as number of chocolate chips.

The class constructor lets you write the code for “constructing” the instance, to get it into the right starting point.

Code

import arcade


class MyGame(arcade.Window):
    def __init__(self, width, height, title):
        super().__init__(width, height, title)
        arcade.set_background_color(arcade.color.WHEAT)
        self.title = title

    def on_draw(self):
        arcade.start_render()
        arcade.draw_text(self.title, 200, 300, arcade.color.BLACK, 12)


def main():
    game1 = MyGame(600, 600, 'Drawing Example')
    arcade.run()


if __name__ == '__main__':
    main()

Analysis

  • Classes can have “constructors”
  • A constructor is a method with a special name – __init__
  • Like all methods, it takes self as a first argument (self is the particular instance being constructed)
  • Like all methods, you can pass arguments to the constructor to use in the construction
  • Setting the bg color is conceptually part of “construction”
  • No need for GAME_TITLE as a constant
  • Instead, use the instance to store the title as an instance attribute
  • ‘self.’ is a way to refer to the instance (“self”) and store a value (an attribute) on it
  • Thus, ‘self.title’ means: “Store a value for title on the instance”
  • Your superclass (e.g. arcade.window) might also have a constructor, so you might have to call that one with super()

Exercises

  1. Comment out the line that calls the superclass constructor. What does PyCharm tell you?

  2. Make the background color something each instance can vary on:

    • Add bgcolor to the constructor arguments, just like title
    • Store it on the self, just like title
    • Use the instance value in set_background_color, just like we used title in draw_text
  3. Do the same for font size.

  4. In the constructor, add “message = ‘Hello’” then add print(message) in the on_draw method. What happens?

Quiz

  1. Is the constructor used to construct classes or to construct instances?
  2. Is __init__ a function or a method?
  3. On what line is the constructor called (i.e. executed)?