Section 17.6 Adding Other Methods to our Class
The key advantage of using a class like
Pointrather than something like a simple tuple
(7, 6)now becomes apparent. We can add methods to the
Pointclass that are sensible operations for points. Had we chosen to use a simple tuple to represent the point, we would not have this capability. Creating a class like
Pointbrings 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
tessobject to perform its
rightmethod and turn 90 degrees. Methods are accessed using dot notation.
Let's add two simple methods to allow a point to give us information about its state. The
getXmethod, when invoked, will return the value of the x coordinate. 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
getXmethod 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
selfas their first parameter. Again, this serves as reference to the object itself which in turn gives access to the state data inside the object.
Note that the
getXmethod simply returns the value of
self.xfrom the object itself. In other words, the implementation of the method is to go to the state of the object itself and get the value of
x. Likewise, the
getYmethod looks the same.
Let's add another method,
distanceFromOrigin, to see better how methods work. This method will again not need any additional information to do its work. It will perform a more complex task.
Notice that the caller of
distanceFromOrigindoes not explicitly supply an argument to match the
selfparameter. This is true of all method calls. The definition will always have one additional parameter as compared to the invocation.
You have attempted of activities on this page.