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
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,
y. Finally we add an action function that can be used later (the
For our example, let’s make a class called a
Human will have several methods such as
chew_bubblegum. It will also have several attributes such as
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:
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):
__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
>>> 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
>>> 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!