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.
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()
- Classes can have “constructors”
- A constructor is a method with a special name –
- Like all methods, it takes
selfas a first argument (
selfis 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
titleon the instance”
- Your superclass (e.g.
arcade.window) might also have a constructor, so you might have to call that one with
Comment out the line that calls the superclass constructor. What does PyCharm tell you?
Make the background color something each instance can vary on:
bgcolorto the constructor arguments, just like
- Store it on the
self, just like
- Use the instance value in
set_background_color, just like we used title in
Do the same for font size.
In the constructor, add “message = ‘Hello’” then add
on_drawmethod. What happens?
- Is the constructor used to construct classes or to construct instances?
__init__a function or a method?
- On what line is the constructor called (i.e. executed)?