How do modules and packages work in Python?
As a powerful programming language, Python has a rich standard library and also supports custom modules and packages, which makes program organization and reuse simpler and more efficient. This article will introduce the basic concepts of modules and packages in Python and illustrate how they work through specific code examples.
1. The concept and use of modules
In Python, a module is a file containing functions, variables and classes. Each Python file can be regarded as an independent module and introduced into other programs for use through the import statement. The following is a simple module example, saved as an example_module.py file:
# example_module.py PI = 3.14159 def circle_area(radius): return PI * radius * radius def square_area(side_length): return side_length ** 2
In another program, you can use the import statement to import this module and call the functions in it:
import example_module print(example_module.circle_area(2)) print(example_module.square_area(4))
Run The output results of the above code are 12.56636 and 16 respectively.
2. The Concept and Use of Packages
Package is a way to organize multiple modules. In Python, a package is a folder containing an __init__.py file. The __init__.py file can be an empty file, but its existence indicates that the folder is a package. The following is a simple package example, containing two modules circle.py and square.py, and an empty __init__.py file:
my_package/ __init__.py circle.py square.py
The contents of the circle.py file are as follows:
# circle.py PI = 3.14159 def area(radius): return PI * radius * radius
# square.py def area(side_length): return side_length ** 2
import my_package.circle import my_package.square print(my_package.circle.area(2)) print(my_package.square.area(4))
from example_module import circle_area print(circle_area(2))
import example_module as em print(em.circle_area(2))
from my_package import * print(circle.area(2)) print(square.area(4))
import sys print(sys.path)
The above is the detailed content of How do modules and packages work in Python?. For more information, please follow other related articles on the PHP Chinese website!