Lesson 7
Objects and Dictionaries
Chapter 3: Object methods
Object methods
Now, let us explore the concept of object
s 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 |
|
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 |
|
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.