Methods are the workhorses of classes. They are where you turn to get things done.
They work just like functions, except they work on the class object. Let’s look at the example from the previous lesson – Point
:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def get_location(self):
"""Returns the location of the point as a tuple."""
return self.x, self.y
The Point
class has two variables, x
and y
, and one method, get_location()
.
This get_location()
function doesn’t do much here, simply returning the x
and y
attributes. We could make something a bit more interesting, however:
import math
class Point:
# ... Fill in the other code here
def difference(self, other):
"""
This takes another point (other) and finds the difference
between this point and the other.
The formula for the difference (or distance) between
two points is D = sqrt(dx*dx + dy*dy)
ref: http://www.mathopenref.com/coorddist.html
"""
dx = self.x - other.x
dy = self.y - other.y
return math.sqrt((dx * dx) + (dy * dy))
The difference
method, when executed on a point and given another point, returns the distance between those two points.
>>> a = Point(0, 3)
>>> b = Point(4, 0)
>>> a.difference(b)
5.0
Horray! Pythagoras was a pretty smart, and so are we!
Now let’s try some methods on our Human
class as well. (Note: you should probably write this into a file first, rather than directly into the Python console, for sanity.)
class Human:
def __init__(self, name, hair_color, shoe_size=10):
# Here we set the attributes passed from creation
self.name = name
self.hair_color = hair_color
self.show_size = shoe_size
# Here we set the attributes that are the same
# for each Human
self.age = 0
self.position = Point(0, 0)
def walk(self, dx, dy):
"""Walks in the given dx and dy direction."""
self.position.x += dx
self.position.y += dy
def talk(self, sentence):
"""Speak the given sentence aloud."""
print(sentence)
def chew_bubblegum(self):
"""Chew some bubblegum. We assume that
the Human has some bubblegum already."""
print("*smack* *smack* *pop*")
Now that we have several methods to play with!
>>> bob = Human("Bob", "brown")
>>> bob.talk("Howdy")
Howdy
>>> bob.chew_bubblegum()
*smack* *smack* *pop*
>>> bob.position.get_location()
(0, 0)
>>> bob.walk(3, 7)
>>> bob.position.get_location()
(3, 7)