An Introduction to Classes

1. Introduction

Classes are a part of "Object Oriented Programming". You've already used classes in Python including "Lists" and "Strings". Classes are a powerful part of designing software that is easy to to use and support as you can "encapsulate" functionality within the class as you already have with functions. With a class you can encapsulate related functions that operate on the same type of data. Now you'll learn to create your own classes.

A class is a grouping of functions and variables. You can then create "instances" of a class and call functions within the class to modify the variables within the class. You've already done this with strings. For instance, in the following code we create a string and then split the string based on slashes. The sequence of characters are a variable within the string and then the "split()" function is a function within the class.


Classes are a powerful way to expand programs for a large variety of applications. This includes spatial modeling. The idea is that you can create a "class" that defines how a particular type of objects behave. The objects can represent people, animals, trees, buildings, or just about anything. The classes allow us to define the properties (also referred to as variables) for each type (or class) of object. The class for people might have variables like height, sex, weight, and income range. A class for trees might have species and height. These variables can be hidden inside the class so we don't have to constantly pass them into the functions that work on the objects. Even more importantly, we can create lists of many objects and manage them in the same way.

The example below shows how to create a very simple class.

2. Test Class

Below is about the simplest class you can create in Python. The __init__ function creates the object and allows you to store any parameters you like into the object ("self"). The __init__ function should also do any other initialization steps needed such as opening files, starting counters, etc.

The other function calls in a class can access the values stored in self.

class TheClass:
	def __init__(self, AdditionalParameters):

		self.AdditionalParameters=AdditionalParameters # Save this for later

	def PrintSelf(self):
		print(self.AdditionalParameters) # functions can access data stored in "self"

3. Calling The Class

To create an object from a class, just call the class and pass it any parameter needed. Then, you can access the functions in the class just as we have been all along in Python.

TheObject=TheClass("This is cool")


Additional Resources:

Python Documentation: Classes

© Copyright 2018 HSU - All rights reserved.