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

Chapter 3: Object methods

Object methods

face Josiah Wang

Now, let us explore the concept of objects further.

What if objects can be more than just a data type? What if we can actually get objects to do things?

For example, a computer can be turned on or shut down. A phone can ring. You can set the time on a clock.

Would it not be great if our programs can be written in such a way that it mirrors the real world, since everything is an object in Python anyway? Rather than talking in terms of variables and expressions and functions, it can be easier to imagine concrete objects and modelling them directly into your program as objects.

The following codes will not work (at least not in its current form!!) But it serves to illustrate my point. Do you find this code naturally easy to understand and even visualise in your mind?

my_computer.shut_down()

if phone.is_ringing():
    phone.answer()

clock.set_time("20:35")

alarm.set(date="10/09/2021", time="09:00")

Fortunately, what I described is not a fantasy. You can actually bind ‘actions’ to objects. Such actions are known as object methods.

All objects can have methods. A method is essentially a function, but the function belongs to the object and can operate on the object.

Here is an example code that works. Treat sentence, words and word as objects, and imagine that you can perform an ‘action’ on them. While you read the code, try to imagine the objects (sentence, words and word), and imagine the sentence being ‘split’ and a word being ‘capitalized’

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())

Contrast this to how you might just write functions and pass objects as arguments, like how we have been mainly doing. See and feel the difference?

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))

Like functions, methods can return a value or simply return None.

Some methods can also modify the object itself. You have used one of these so far: my_list.append("new item") will modify the value of my_list, without needing to return anything. Some people call such methods mutator methods.