Lesson 8
Making Objects the Main Star!
Chapter 6: Object methods
Object methods revisited
Earlier, you created class
definitions to represent objects as a complex data type, i.e. an object can have some attributes associated with it. 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 |
|
With methods, it reads more naturally since the ‘action’ is bound to the object.
1 2 3 4 5 6 |
|
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!