In Python, in order to write easy to maintain code, we will split the code into different files, so that the code contained in each file will be relatively reduced. In Python, a The py file is called a Module.
Benefits of code modularity:
(1) Simplified problem solving
Reduce the code complexity and split the code into different files. Each file only needs to consider the solution of its sub problems, not the solution of the whole problem.
(2) Improve code maintainability
Reduce the dependence between codes, reduce the impact of modifying one file on other files, and improve the possibility of parallel development between different files.
(3) Improve reusability between codes
After a module is written, it can be referenced by other modules. When programming, you can introduce other modules, including Python built-in modules and third-party modules. Improve code reusability and development efficiency.
(4) Reduce code conflicts
The module provides an independent namespace. The advantage of independent namespace is that it can avoid the conflict between function name and variable name. Functions and variables with the same name can be placed in different modules. Therefore, when we write the module ourselves, we don't have to consider that the name will conflict with other modules. However, be careful not to conflict with the names of built-in functions.
First, the creation of modules.
Create a py file, put the implementation code logic into this file, that is, complete the creation of the Module. One py file is a Module.
# utils.py module def max_num(a, b): if a >= b: return a else: return b def min_num(a, b): if a > b: return b else: return a
Two. Module import
1,import
After the module is created, it can be imported with the import keyword, such as import utils
When this command is executed, Python will find the corresponding module from the following steps:
(1) Search in the current directory.
(2) Search the module once in the environment variable PYTHONPATH.
(3) Find it in the lib Library under the Python installation path.
The above path can use sys Path, located in the sys module. sys.path is an environment variable of Python and a list of paths Python uses to search for modules.
import sys print(sys.path)
Output:
['/tmp/box/24', '/usr/local/python3/lib/python39.zip', '/usr/local/python3/lib/python3.9', '/usr/local/python3/lib/python3.9/lib-dynload', '/usr/local/python3/lib/python3.9/site-packages']
In order to find the created module, you need to put the module in one of the above paths, because Python will only find the module in these paths. If the module is not created in these paths, the corresponding module cannot be found, and there is no way to apply the objects and methods in the module.
#Import module utils import utils print(utils.max_num(4, 5)) print(utils.min_num(4, 5))
Output:
5
4
2,from mudule_name import name(s)
Directly import the objects in the module. Format: from module name import method name / object name
from utils import max_num, min_num print(max_num(4, 5)) print(min_num(4, 5))
Output:
5
4
Use the from module name import * to import all objects under the module
from utils import * print(max_num(4, 5)) print(min_num(4, 5))
Output:
5
4
3,from module_name import names as alt_name
Objects and methods in the module can also be named aliases. Format: from module name import method name 1 / object name 1 as alias 1, method name 2 / object name 2 as alias 2
from utils import max_num as max_n, min_num as min_n print(max_n(4, 5)) print(min_n(4, 5))
Output:
5
4
4,import module_name as alt_name
You can name an alias for the entire module, such as:
import utils as ul print(ul.max_num(4, 5)) print(ul.min_num(4, 5))
Output:
5
4
5. Module introduction containing a single class
#Create module Car Py, including a Car class class Car: def __init__(self, mk, md, y, c): self.make = mk self.model = md self.year = y self.color = c self.mileage = 0 def get_description(self): description = f'{self.year} {self.color} {self.make} {self.model}' print(description) def get_mileage(self): print(f"This car has {self.mileage} miles on it") def update_mileage(self, mile): self.mileage = mile
Introduce Car class:
from car import Car my_car = Car('audi', 'a4', 2016, 'white') my_car.get_description() my_car.update_mileage(30) my_car.get_mileage()
Output:
2016 white audi a4
This car has 30 miles on it
6. The introduced class contains multiple modules
#Create Car Py module, including Car class and its inherited class ElectricCar class Car: def __init__(self, mk, md, y, c): self.make = mk self.model = md self.year = y self.color = c self.mileage = 0 def get_description(self): description = f'{self.year} {self.color} {self.make} {self.model}' print(description) def get_mileage(self): print(f"This car has {self.mileage} miles on it") def update_mileage(self, mile): self.mileage = mile class ElectricCar(Car): def __init__(self, mk, md, y, c): super().__init__(mk, md, y, c) self.battery_size = 100 def get_battery(self): print(f"This car has {self.battery_size} -kWh battery.")
Import multiple classes:
from car import ElectricCar, Car my_car = Car('audi', 'a4', 2016, 'white') my_car.update_mileage(30) my_car.get_mileage() my_tesla = ElectricCar('tesla', 'model 3', 2018, 'white') my_tesla.get_description() my_tesla.get_battery()
Output:
This car has 30 miles on it
2018 white tesla model 3
This car has 100 -kWh battery.
Import the whole module and use import car
Import all classes in the module and use from car import*
3, Package
With the increase of modules, all modules are placed in the same directory, which is difficult to manage. Therefore, the concept of package is introduced.
1. Package creation
For modules with similar names or functions, you can use the function of module grouping management in Python, use the hierarchical file structure of operating system files, and put the modules in a directory folder to form a package.
As shown in the figure, utils 1.0 exists in the folder {pkg Py and utils2 Py two files. (pkg is a package, and utils1.py and utils2.py are two modules)
#utils1.py module def max_num(a, b): if a >= b: return a else: return b def min_num(a, b): if a > b: return b else: return a
#utils2.py module def sum_num(a, b): return a + b def abs_num(a): if a >= 0: return a else: return -a
2,import module_names[,...]
Use the import package name The module name is introduced into the module in the package
import pkg.utils1,pkg.utils2 print(pkg.utils1.max_num(4, 5)) print(pkg.utils2.sum_num(4, 5))
Output:
5
9
3,from pakage_name import module_name[,...]
Use the from package name to import module name 1 and module name 2 to import modules in the package
from pkg import utils1, utils2 print(utils1.max_num(4, 5)) print(utils2.sum_num(4, 5))
Output:
5
9
4,from module_name import names[,...]
Introduce the object of the module in the package and use the from package name Module name import object name
from pkg.utils1 import max_num print(max_num(4, 5))
Output:
5
5,from module_name import names as alt_name
Create an alias for the object of the module in the package, using the from package name Module name import object name as alias
6,from pakage_name import module_name as alt_name
Create an alias for the entire module in the package, using the from package name import module name as alias
Or import package name Module name as alias