Salvatore Lopiparo

Senior Software Engineer

Super Simple Python – Classes Pt. 2: Methods

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)

Super Simple Python – Classes Part 1: Creation and Attributes

Time for class! Other programming lessons are second class! This lesson is in a class of it’s own!

Ok, I’ll stop.

A class is a programming object that groups together common functions (called methods) and variables (called attributes) that effect and define that object. Here is a very simple class for a point on a grid:

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

In our Point class, first we give it a name, then define how to create one using the __init__ method, in which we give it two attributes, x and y. Finally we add an action function that can be used later (the get_location method).

For our example, let’s make a class called a Human. Our Human will have several methods such as walk, talk, and chew_bubblegum. It will also have several attributes such as name, age, hair_color and shoe_size. In this lesson, we’ll deal with creation of the class and it’s attributes.

There are a few things we must do to define a class. First, we define our class with a name:

class Human:

Next, we need to show how our Human is created using the __init__ method (which stands for initialize). The __init__ method is a special function that classes will always run first when creating an instance of the class.

class Human:
    def __init__(self, name, hair_color, shoe_size=10):

In our __init__, we need to initialize all of our attributes (or variables attached to our object). We define __init__ just like any other function, except indented for the class. The variables in the __init__ method will be used to create an object from the class.

There is one extra argument, called self, that gives the method a reference to the object that is being created. In other words, the self variable is a reference to the current instance of the class. self must always be the first argument in a class method.

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 all Humans
        self.age = 0

Here, we’ve defined our class Human. Now let’s create a couple Humans!

>>> bob = Human("Bob", "brown")
>>> bob
<Human object at 0x02A8EB30>
>>> joe = Human("Joe", "black", shoe_size=13)
>>> joe
<Human object at 0x02A8EF30>

Awesome! We have our Human objects! The hexidecimal number (i.e. 0x02A8EF30) included in with each object shows where the object is in memory, which we tend to not worry about. Now to use the attributes of our objects, we use the format object_name.attribute:

>>> print(bob.name)
Bob
>>> print(bob.shoe_size)
10
>>> print(bob.age)
0
>>> print(joe.name)
Joe
>>> print(joe.shoe_size)
13
>>> print(joe.hair_color)
black

We now have the shell of a Human! It only has attributes so far, so next time we will give our Humans something to do!