Previous Lesson Table of Contents Next Lesson

Suppose you are a store owner, and you wanted to keep track of your items in inventory. Although not all of your items are the same, they share some common characteristics, or attributes, such as price or item ID or item name.

In Python, we can represent a store item using classes:

class Item:
    def __init__(self, item_id, item_name, item_price):
        self.item_id = item_id
        self.item_name = item_name
        self.item_price = item_price

Although we’re just getting started with this class, there is already a lot to unpack with this code. First, in order to create a class, we must use the class keyword followed by the class name and then a colon to initiate the body of the class definition.

As with functions, note that we tab in the class definition at least once so that Python knows that this code is for the Item class.

We then have this weird looking __init__ function (or method, when the function is defined under a class). To begin, in order to use this class to represent each item in our inventory, we have to create an instance or instantiate the class with the values corresponding to item’s attributes, which are item_id, item_name, and item_price.

During instantiation, Python automatically calls this __init__ function, during which we instantiate our class. This instance is represented by the self parameter in the function. To create and assign attributes, we use self.[attribute_name] followed by an = sign to provide a value, which could be a number, string, or even another class instance!

Notice that unlike functions that we have seen up and until this point, there is no return statement. This is because Python will implicitly handle outputting a new instance when we create it, as illustrated below:

item = Item(1, "car", 2)
print(item)

To initialize an instance, we treat the class name as a function and pass in all of the parameters (except for self, which Python implicitly handles). This syntax will return a new instance of the class, as seen in the output:

<__main__.Item object at 0x7fd425bccd30>

Don’t focus on the specifics of the output for now, but the important point to recognize is that we have created an Item object.

Instance attributes are freely accessible to us using the same self.[attribute_name] convention as before, except we use the variable name corresponding to the instance instead of self, for example:

item = Item(1, "car", 2)
print(item.item_id)

This will output the item_id attribute of our Item instance, which in this case is:

1

Now for each item, let’s suppose you want to compute the total cost of purchasing n items. The total cost is then n * [item_price], but instead of having to write that out every time, we can create a method for this:

class Item:
    def __init__(self, item_id, item_name, item_price):
        self.item_id = item_id
        self.item_name = item_name
        self.item_price = item_price

    def compute_cost(self, n):
        return self.item_price * n

Note that our new function compute_cost accepts self as its first argument. In fact, it’s the first argument that Python will pass into any method, followed by any other arguments passed into the function.

In addition, because we create an item_price attribute when we instantiate an Item, this attribute is available to us in other methods. To call our method, we can access it like we did with attributes by using self.[method_name], followed by (), between which we pass in our arguments. Here is the method in action now:

item = Item(1, "car", 2)
print(item.compute_cost(2))

Wait, didn’t compute_cost have two arguments? Why did we pass in only one? This is because Python automatically infers that self refers to item, so it will implicitly pass in item as the first argument. The second argument is therefore the number 2. Each item costs 2, so purchasing n = 2 will output a cost of:

4

Let’s now practice using classes in Python:

  • Create a Person class with the following attributes: age (number) and name (string). What parameters do you need to pass into your __init__ method? (solution)

  • Create a method called years_until_legal, which computes the number of years until a person turns 21, which is the difference between age and 21. What parameters do you need to pass into this method? How do you then compute and output that difference? (solution)

Please note that what we have discussed only scratches the surface. There is a lot more that we can discuss, but this should hopefully get you comfortable with the concept initially! If you are, then feel free to move on to Lesson 6!