David Abel

Portrait


Python Tutorial

python logo

This tutorial is intended as an introduction to Python for folks with some prior programming experience.

Section 4: Classes (oop.py)

Python was not designed for large scale Object Oriented Projects, but it does have some support. A class in python is relatively simple:

class <class_name>:
    def __init__(self, param_one):
        # Constructor body
        self.field = param_one

Some important things to note:

  1. __init__ is a special function name reserved for the constructor. It will be called automatically when a new instance of the class is created.

  2. self is a reserved term used inside of a class that passes around a reference to the current instance, allowing access to classwide variables. It is always passed in as the first parameter to every class method. Note: make sure you include self as the first argument to every method in a class (if you get an error related to a class method, make sure you're passing self as the first parameter!).

In this section, you will build an address book class to learn some basic python OOP. To begin, make an Entry class that defines the data type to be stored in the address book. This class should be relatively simple. Pass in the data you would like to store in each entry, and store them in classwide variables. For instance:

class Entry:
    def __init__(self, phone):
        self.phone_num = phone

To create an instance of an object of a new class, do the following:

>>> new_instance = ClassName(param_one, param_two)

For instance, we can make a new Entry instance as follows:

>>> new_entry = Entry("555-777-9999")

Now make an AddressBook class that takes as input a dictionary of Entry objects, where the key is the name of the person, and the value is an Entry object. Also include a get_entry method that takes as input a key and returns the value associated with that key, and an add_entry method that takes as input a new name and Entry pair and stores it in the address book. Lastly, rewrite the __str__ method of AddressBook to print out the entire contents of the dictionary in an easy to read way.

You can do this by describing each Entry object in the AddressBook by a single string:

def __str__(self):
    return str(self.entry_one) + " | " + str(self.entry_two)

Remember to include self as the first parameter in all of these method definitions. Python automatically passes in a pointer to the instance as self.

Try creating a few Entry objects and an AddressBook. I suggest doing this in a main() method, as is python standard.

A basic main function typically looks like:

def main():
    # function body, create instances, call other functions, etc.
if __name__ == "__main__":
    main()

This last bit ensures that the main method is only called if we run this file explicitly. If we import this file from another python file, the python variable __name__ is unequal to "__main__", and main will not be called.

Try printing a few of your Entry objects. You will likely see the following:

>>> a = Entry("555-555-5555","Sam")
>>> print a
<__main__.Entry instance at (hex_numbers)>

This is because we haven't told python how to print Entry objects, so the interpreter defaults to printing the type and memory address. We can change this by implementing the __str__ method in the Entry class. For instance, try:

def __str__(self):
    return "Phone: " + str(self.phone_num)

You can add on to this method however you'd like depending on what data you added. There are lots of functions that may be overwritten, such as __add__ (defines default behavior for "+"), and __cmp__ (defines default behavior for comparison, i.e. "==").

Now let's write a subclass of Entry that holds on to a bit more data. Create a class called LargeEntry in the same file.

Subclassing in python is done as follows:

class (SuperClass):
    def __init__(self, param_one, param_two):
        SuperClass.__init__(self, param_one)
        self.field_two = param_two

Try making the LongEntry class and adding a few LongEntry objects to your address book.

< Previous Section Next Section >