Lecture Date: Wednesday, March 2
Since the first day we began coding in this class, we have been using (or “calling”) methods and functions to do various things:
1 2 3 4 5 6 7 8 9
()s after it are either methods or functions. Methods are, in effect, verbs in our programs. They tell objects to do things, change their state somehow, or provide us with information. In the code above, we are telling the
t to do some specific tasks. Each one of those tasks is a method. A function is a bit of code that we separate out to do a particular task in a very similar way to a method, but the difference is it is not directly tied to an object and called with a period.
def draw_square() above is a function. We are going to focus on functions in this class.
The things inside the parentheses are called parameters or arguments. Parameters provide extra information to the method to tell it how to perform a method or what data it should act on. So, when we tell
t to do
forward(100), we are saying that
100 is important information in order for the method to execute properly.
Methods form the basis of many programs for several reasons:
- Code reuse: Often you’ll have a bit of code you want to use over and over. Methods make that happen in a very nice way, while also allowing for modification with parameters.
- Organization: It’s a lot easier to see what’s going on when you read code when you have a set of methods saying what they do! Reading
backward()in the Turtle code is completely understandable - having the code to do those things might not be. It’s an added layer of abstraction.
- Testing: Once you verify a function is correct and working, you can move on to other parts of your system.
Another thing to know about functions is how parameters are passed into them.
- Pass by Value: This is how non-mutable types are passed (or given) to a function. A full copy of the variable (value and everything) is sent to the function. Any changes made to the variable passed in ARE NOT REFLECTED back where the function was called.
- Pass by Reference: This is how mutable types are passed to a method. A pointer (think “road sign”), which is a copy of the memory address of the object, is sent to the function. Any changes made to the variable passed in ARE REFLECTED back where the function was called.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
No Audio Today