Section 13.8 Adding Other Methods to our Class
The key advantage of using a class like
Rectangle
rather than something like a simple list [7, 6]
now becomes apparent. We can add methods to the Rectangle
class that are sensible operations for rectangles. Had we chosen to use a simple list to represent the rectangle, we would not have this capability. Creating a class like Rectangle
brings an exceptional amount of “organizational power” to our programs and to our thinking. We can group together the sensible operations and the kinds of data they apply to, and each instance of the class can have its own state.A method behaves like a function, but it is invoked on a specific instance. For example, with a turtle named
tess
, tess.right(90)
asks the tess
object to perform its right
method and turn 90 degrees. Methods, like attributes, are accessed using dot notation.Let’s add two simple methods to allow a point to do calculations with the information about its state. The
area
method, when invoked, will return the value of the rectangle’s area. The implementation of this method is straight forward since we already know how to write functions that return values. One thing to notice is that even though the area
method does not need any other parameter information to do its work, there is still one formal parameter, self
. As we stated earlier, all methods defined in a class that operate on objects of that class will have self
as their first parameter. Again, this serves as reference to the object itself, which in turn gives access to the state data inside the object. We will also write a similar perimeter
method that returns the rectangle’s perimeter.Let’s add another method,
diagonalLength
, to see better how methods work. This method will again not need any additional information to do its work, but it performs a more complex task.Notice that the caller of
diagonal_length
does not explicitly supply an argument to match the self
parameter. This is true of all method calls. The definition will always have one additional parameter as compared to the invocation. (You can think of self
as a placeholder for the object that precedes the dot in the invocation.)