{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "< [Classes](PythonIntroCh7.ipynb) | [Contents](PythonIntro.ipynb) | [File I/O](PythonIntroCh9.ipynb) >" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 8. Modules\n", "## 8.1 Introduction\n", "Last lesson we covered the killer topic of Classes. As you can remember, classes are neat combinations of variables and functions in a nice, neat package. Programming lingo calls this feature encapsulation, but regardless of what it is called, it's a really cool feature for keeping things together so the code can be used in many instances in lots of places. Of course, you've got to ask, \"how do I get my classes to many places, in many programs?\". The answer is to put them into a module, to be imported into other programs." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8.2 Module? What's a Module?\n", "A module is a Python file that (generally) has only definitions of variables, functions, and classes. For example, a module might look like this, which we store in a file `moduletest.py`:\n", "```Python\n", "### EXAMPLE PYTHON MODULE\n", "# Define some variables:\n", "numberone = 1\n", "ageofqueen = 78\n", "\n", "# define some functions\n", "def printhello():\n", " print(\"hello\")\n", " \n", "def timesfour(input):\n", " print(eval(input) * 4)\n", " \n", "# define a class\n", "class Piano:\n", " def __init__(self):\n", " self.type = input(\"What type of piano? \")\n", " self.height = input(\"What height (in feet)? \")\n", " self.price = input(\"How much did it cost? \")\n", " self.age = input(\"How old is it (in years)? \")\n", "\t\n", " def printdetails(self):\n", " print(\"This piano is a/an \" + self.height + \" foot\", end=\" \")\n", " print(self.type, \"piano, \" + self.age, \"years old and costing\\\n", " \" + self.price + \" dollars.\")\n", "```\n", "\n", "As you see, a module looks pretty much like your normal Python program.\n", "\n", "So what do we do with a module? We `import` bits of it (or all of it) into other programs.\n", "\n", "To import all the variables, functions and classes from `moduletest.py` into another program you are writing, we use the `import` operator. For example, to import `moduletest.py` into your main program (`mainprogram.py`), you would have this:\n", "\n", "```Python\n", "### mainprogam.py\n", "### IMPORTS ANOTHER MODULE\n", "import moduletest\n", "```\n", "\n", "This assumes that the module is in the same directory as `mainprogram.py`, or is a default module that comes with Python. You leave out the `.py` at the end of the file name - it is ignored. You normally put all `import` statements at the beginning of the Python file, but technically they can be anywhere. In order to use the items in the module in your main program, you use the following:\n", "\n", "```Python\n", "### USING AN IMPORTED MODULE\n", "# Use the form modulename.itemname\n", "# Examples:\n", "print(moduletest.ageofqueen)\n", "cfcpiano = moduletest.Piano()\n", "cfcpiano.printdetails()\n", "```\n", "\n", "As you see, the modules that you import act very much like the classes we looked at last lesson - anything inside them must be preceded with `modulename.` for it to work." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8.3 More module thingummyjigs (in lack of a better title)\n", "Wish you could get rid of the `modulename.` part that you have to put before every item you use from a module? No? Never? Well, I'll teach it to you anyway.\n", "\n", "One way to avoid this hassle is to import only the wanted objects from the module. To do this, you use the `from` operator. You use it in the form of `from modulename import itemname`. Here is an example:\n", "\n", "```Python\n", "### IMPORT ITEMS DIRECTLY INTO YOUR PROGRAM\n", "\n", "# import them\n", "from moduletest import ageofqueen\n", "from moduletest import printhello\n", "\n", "# now try using them\n", "print(ageofqueen)\n", "printhello()\n", "```\n", "\n", "What is the point of this? Well, maybe you could use it to make your code a little more readable. If we get into heaps of modules inside modules, it could also remove that extra layer of crypticness.\n", "\n", "If you wanted to, you could import everything from a module in this way by using `from modulename import *`. Of course, this can be troublesome if there are objects in your program with the same name as some items in the module. With large modules, this can easily happen, and can cause many a headache. A better way to do this would be to import a module in the normal way (without the `from` operator) and then assign items to a local name:\n", "\n", "```Python\n", "### ASSIGNING ITEMS TO A LOCAL NAME\n", "\n", "# Assigning to a local name\n", "timesfour = moduletest.timesfour\n", "\n", "# Using the local name\n", "print(timesfour(565))\n", "```\n", "\n", "This way, you can remove some crypticness, AND have all of the items from a certain module.\n", "\n", "A final handy way to import modules is with an alias. Maybe you want to change a name because you've already used the same name for something else in your program, another module you imported uses the same name, or maybe you want to abbreviate a longer name that you use a lot. We can then use the `as` operator. That looks like this:\n", "\n", "```Python\n", "### IMPORT A MODULE WITH AN ALIAS\n", "# import module\n", "import moduletest as mt\n", "\n", "# use module\n", "print(mt.age)\n", "cfcpiano = mt.Piano()\n", "cfcpiano.printdetails()\n", "```\n", "\n", "## 8.4 Conclusion\n", "That's it! A very simple lesson, but now you can organise your programs very neatly. In fact, now it is incredibly easy to make programs that can grow in complexity without ending up with one cryptic file that is full of bugs.\n", "Modules are great for importing code. Next lesson, we learn about file input and output, and the saving of information inside classes, to be retrieved later. Will be great!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "< [Classes](PythonIntroCh7.ipynb) | [Contents](PythonIntro.ipynb) | [File I/O](PythonIntroCh9.ipynb) >" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.4" } }, "nbformat": 4, "nbformat_minor": 4 }