Every Python file is a module.
You can import modules from other files, which is the basis of any medium-complexity program, because it promotes wise organization and code reuse.
In a typical Python program, a file serves as the entry point. Other files are modules and expose functions that we can call from other files.
filedog.py
Contains the following code:
def bark():
print('WOF!')
We can useimport
, And then we can use dot notation to refer to the function,dog.bark()
:
import dog
dog.bark()
Or we can usefrom .. import
Syntax and call the function directly:
from dog import bark
bark()
The first strategy allows us to load all the content defined in the file.
The second strategy allows us to choose what we need.
These modules are specific to your program, and import depends on the location of the file in the file system.
Suppose you putdog.py
in alib
subfolder.
In that folder, you need to create a file named__init__.py
. This tells Python that the folder contains modules.
Now you can choose, you can importdog
Fromlib
:
from lib import dog
dog.bark()
Or you can refer todog
Import module specific functions fromlib.dog
:
from lib.dog import bark
bark()
More python tutorials:
- Introduction to Python
- 在macOS上安装Python 3
- Run Python program
- Python 2 and Python 3
- Basics of using Python
- Python data types
- Python operators
- Python string
- Python boolean
- Python numbers
- Python, accepts input
- Python control statements
- Python list
- Python tuple
- Python set
- Python dictionary
- Python functions
- Python objects
- Python loop
- Python module
- Python class
- Python standard library
- Debug Python
- Python variable scope
- Python, accept parameters from the command line
- Python recursion
- Python nested functions
- Python Lambda function
- Python closure
- Python virtual environment
- Use Python to use GoPro as a remote webcam
- Python, how to create a list from a string
- Python decorator
- Python Docstrings
- Python introspection
- Python notes
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get detailed information of a file
- Python, how to check if a file or directory exists
- Python exception
- Python, how to create a directory
- Python, how to create an empty file
- Python, `with` statement
- Python, create a network request
- Python, use `pip` to install third-party software packages
- Python, read file content