How to Import a Python Class From an Interactive Shell
Python is used, most of the time, as an interpreted language. As a program executes, the interpreter converts each statement on the fly to an internal bytecode representation; the Python virtual machine executes those bytecodes immediately. The interpreter offers an interactive shell where you can enter commands and examine the values of variables. You can import a Python class defined in an external file from the interactive shell, to use the methods in that class in subsequent commands.
Instructions
-
-
1
Segregate the Python code for the class(es) you want to import in a separate file. For example, call a text editor to open a new file named "ExternalClass.py", then type the following lines into the file:
class ExternalClass():
def externalMethod(self):
return 'the external class executed'
Save the contents of the file and exit the text editor.
-
2
Launch the Python interpreter by clicking "Start," then typing "cmd" into the search box. Type "python" into the newly opened Command window and press "Enter." The interpreter will present you with a prompt awaiting your commands.
-
-
3
Type the following line into the interpreter's interactive prompt to import the external class:
import ExternalClass
Press "Enter." At that point, all the attributes and methods defined in the external class (method "externalMethod()" in the example) will be usable from the interactive Python shell.
-
1