Read section 17.5 in the book and try out the code samples.
Constructors are methods that are automatically called to help create objects. We've already used them:
world = TurtleWorld() michelangelo = Turtle()
These two lines call the constructors in the TurtleWorld and Turtle classes, but they don't call them directly. Instead:
The __init__ method is one of many special methods, meaning it has some pre-defined use in Python. (Here it's the constructor.) Let's do an example by updating our Recipe class:
class Recipe(object): """Models a recipe to make food.""" def __init__(self): self.name = "" self.ingredients = [] self.steps = []
Add this constructor to your code from before, now it is automatically invoked when we create a Recipe object:
>>> fake_chx_parm = Recipe() >>>
As a general rule, you should never invoke special methods directly! They will automatically get called by Python when you do something else.
Three fields are already set!
>>> fake_chx_parm = Recipe() >>> fake_chx_parm.steps [] >>> fake_chx_parm.name '' >>>
The name field isn't correct, so we need to set this separately, probably right after we create the recipe.
>>> fake_chx_parm = Recipe() >>> fake_chx_parm.name = "Microwave Chicken Parm"
There's a much better way to initialize fields, though! Instead of setting them after, we can generalize the constructor by adding parameters. Let's do this to Recipe's constructor:
def __init__(self, name): self.name = name self.ingredients = [] self.steps = []
Now we can initialize all fields in one line:
>>> fake_chx_parm = Recipe("Microwave Chicken Parm") >>> fake_chx_parm.add_ingredient("5 frozen chicken nuggets") ...