Write a program using an object
Start to create your object-oriented text-based adventure game
Extend other people’s classes
Create an enemy in the room
Recap Week 3
Extending your knowledge of OOP
Finish your game
End of the course
In the previous activity, you used the randint function to get a random number when moving the turtle objects forward. Functions allow you to give a name to a set of instructions. You can pass data to a function, and, optionally, you can have it return some data as a result.
Have a look at this example. The following function will tell a knock knock joke if you provide the introduction and the punchline:
def tell(intro, punchline):
print("Knock knock")
print("Who's there")
print(intro)
print(intro + " who")
print(punchline)
You could call this function by writing this line of code passing the intro and punchline of the joke:
tell("Atch", "Sounds like you've got a cold!")
When you programmed the turtles, you used methods such as goto(), which are very similar to functions. The difference is that a method is called on an object, which means that as well as being able to receive data from outside, a method can use all of the data stored inside the object as well.
Here’s what the same joke might look like if a Joke object had been defined with a tell() method.
my_joke = Joke("Atch", "Sounds like you've got a cold!")
my_joke.tell()
If you type in this code and try to run it, you will receive an error:
NameError: name 'Joke' is not defined
This is because you have to first tell Python how to create a Joke object. To do this, Python needs a blueprint for the object. The blueprint you create for an object is called a class. You will create your own classes in week two of the course.