This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 6: Object methods

Object methods revisited

face Josiah Wang

Earlier, you created class definitions to represent objects as complex data types, i.e. objects can have some attributes associated with them. For example, an Email instance can have a subject, body, sender address, recipient addresses, etc.

Now, recall that back in Lesson 7, we discussed that objects can be more than just a data type. They can also have ‘actions’ associated to them (some action that you can ask them to do). Such ‘actions’ are called methods. For example, str and list objects have lots of useful methods.

Without methods, you get code that looks like this.

1
2
3
4
5
6
sentence = "somewhere over the rainbow"
if string_starts_with(sentence, "s"):
    words = split_string(sentence)
    for word in words:
        if string_ends_with(word, "e"):
            print(capitalize(word))

With methods, it reads more naturally since the ‘action’ is bound to the object.

1
2
3
4
5
6
sentence = "somewhere over the rainbow"
if sentence.startswith("s"):
    words = sentence.split()
    for word in words:
        if word.endswith("e"):
            print(word.capitalize())

As another analogy, think of a coffee machine. In the first version (using only functions), you have a coffee machine with no buttons, so you have to put the coffee machine through another high tech machine that can analyse the machine’s properties to somehow produce a cup of coffee for you. In the second version (using methods), you simply tell the coffee machine to brew you coffee by pressing a button, and it brews you a cup of coffee.

In other words, we should just let an object do things it should be able to do itself, since it obviously knows itself best!