13.9. Using Objects in Functions¶
Just like any other data type, we can send an object to a function as an input
value. We did this in the Function Exercises
when we passed a turtle object to the
1 2 3 4 5 6 7 8 9 10
import turtle def draw_square(turtle_name, side_length): for side in range(4): turtle_name.forward(side_length) turtle_name.left(90) bob = turtle.Turtle() draw_square(bob, 40)
Line 8 creates a new
Line 10 calls the
draw_squarefunction and passes
After the function call, control passes to the
draw_squarefunction. In line 3,
turtle_namegets assigned the
The loop executes, and we see the turtle draw a square on the screen.
We can also set up a function to create a new object and return it to the main program.
Assume we defined the same
Dog class we used on the
14 15 16 17 18 19 20 21 22 23
def make_puppy(parent_1, parent_2): puppy_name = parent_1.name + parent_2.name cuteness = parent_1.is_cute or parent_2.is_cute return Dog(puppy_name, 0, cuteness) dog_1 = Dog('Spot', 6, True) # Create one Dog object dog_2 = Dog('Fleas', 2, False) # Create another Dog object new_pet = make_puppy(dog_1, dog_2) # Call make_puppy and return new Dog print(new_pet)
Name of dog: SF, Age of dog: 0 years
Lines 20 and 21 create two new
Line 22 calls the
make_puppyfunction and sends it
Line 14 assigns the objects to the parameters
Line 15 combines the first letters of the parents’ names to make the string for
Line 16 uses a boolean expression to decide if the puppy is cute.
Line 18 creates and returns a new
Control returns to line 22, where the new object is assigned to
13.9.1. Object Scope¶
Within a function, any change made to an object will change the object itself.
In the example above, adding the statement
parent_1.name = "Fido" changes
the property value in the function AND outside of the function. If we
print(dog_1.name) after calling
make_puppy, we would see
Fido appear in the console instead of
parent_1 is NOT a new
Dog object. Instead, it is a new label that
points to the same set of data as
13.9.2. Check Your Understanding¶
bob = turtle.Turtle(), which of the following shows the object
bob used as an argument?
- draw_sprite(bob, 8, 40)
- def draw_sprite(bob, num_legs, leg_length):
- return bob
Which of the following shows the object
trtl_name used as a parameter?
- draw_polygon(trtl_name, 8, 40)
- def draw_polygon(trtl_name, num_sides, side_length):
- return trtl_name