Masthead

Functions, Modules, and Classes

As your code increases in size and complexity, you'll want to spend time working on the structure of the code. The first step is to place code that is repeated into functions in the same file that uses the code. When you start having multiple scripts that need to call the same function, you can place the functions in a "module" which is simply a Python file containing functions. Then, "import" the module into your scripts as you have been doing with libraries. As your code continues to increase in size and complexity, you'll want to create classes to encapsulate functionally. These classes will also be in separate files.

Image of moving code from scripts to fundtions, modules, and classes as they increase in size.

Remember to spend time thinking about the organization of your code and what should be in each function, class, and file. This will keep your code from becoming unsupportable.

© Copyright 2018 HSU - All rights reserved.