Exhibited by Wakagi
custom module
In addition to using the built-in modules provided by the system, we can also write a module for our own programs. A .py
file is a module, so custom modules are very simple, basically equivalent to creating a .py
file. However, it should be noted that if a .py
file is to be used by other codes as a module, the .py
name of the file must follow the naming rules of identifiers.
module search path
Creating a module is very simple. The naming rules of the installation identifier create a .py
file that is a module. But the question is, where do we need to put the created .py
file, and use the statement in the code import
to find this module?
The properties of Python's built-in sys
modules path
list the directories that look for modules when the program is running. You only need to put the modules we created in any of these directories.
import sys
print(sys.path)
[
'C:\\Users\\chris\\Desktop\\Test',
'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\lib',
'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37',
'C:\\Users\\chris\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages'
]
__all__
usage of
When importing all the content in a module is used from <模块名> import *
, it is essentially to find __all__
the properties of this module and __all__
import all the content declared in the properties. If no __all__
attribute is set in this module, all content in this module will be imported at this time.
private members in a module
Variables and functions starting with an underscore in the module _
are private members in the module. When the module is imported, _
variables starting with an underscore will not be imported by default. But it's not mandatory, and _
sometimes it's okay if a code is forced to use a variable starting with . But it is strongly not recommended to use it like this, because it may cause problems.
Summarize
test1.py
: There is no __all__
attribute in the module
a = 'hello'
def fn():
print('我是test1模块里的fn函数')
test2.py
: There are __all__
attributes in the module
x = '你好'
y = 'good'
def foo():
print('我是test2模块里的foo函数')
__all__ = ('x','foo')
test3.py
: There are _
attributes starting with
m = '早上好'
_n = '下午好'
def _bar():
print('我是test3里的bar函数')
demo.py
from test1 import *
from test2 import *
from test3 import *
print(a)
fn()
print(x)
# print(y) 会报错,test2的__all__里没有变量 y
foo()
print(m)
# print(_n) 会报错,导入test3时, _n 不会被导入
import test3
print(test3._n) # 也可以强行使用,但是强烈不建议
__name__
usage of
In actual development, after a developer writes a module, in order to make the module achieve the desired effect in the project, the developer will add some .py
test information to the file by himself, for example:
test1.py
def add(a,b):
return a+b
# 这段代码应该只有直接运行这个文件进行测试时才要执行
# 如果别的代码导入本模块,这段代码不应该被执行
ret = add(12,22)
print('测试的结果是',ret)
demo.py
import test1.py # 只要导入了tets1.py,就会立刻执行 test1.py 代码,打印测试内容
To solve this problem, python has a variable when executing a file __name__
. In Python, when a .py
file is run directly, the value .py
in the file __name__
is __main__
, so it can be judged whether a .py
file is executed directly or imported as a module.
def add(a,b):
return a+b
if __name__ == '__main__': # 只有直接执行这个`.py`文件时, `__name__`的值才是 `__main__`
# 以下代码只有直接运行这个文件才会执行,如果是文件被别的代码导入,下面的代码不会执行
ret = add(12,22)
print('测试的结果是',ret)
Precautions
When customizing modules, you need to pay attention to the fact that the custom module name should not be the same as the system module name, otherwise problems will occur!
Advanced case
[Python] Python realizes the word guessing game-challenge your intelligence and luck!
[python] Python tkinter library implements GUI program for weight unit converter
[python] Use Selenium to get (2023 Blog Star) entries
Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition
[Xiaobai must see] Python word cloud generator detailed analysis and code implementation
[Xiaobai must see] Python crawls an example of NBA player data
[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python
[Xiaobai must see] Python crawler data processing and visualization
[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory
[Must-see for Xiaobai] Use Python to generate a personalized list Word document
Geospatial data processing and visualization using geopandas and shapely (.shp)
Use selenium to crawl Maoyan movie list data
Detailed explanation of the principle and implementation of image enhancement algorithm Retinex
Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis
Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API
Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies
Getting started with crawlers (2): How to use regular expressions for data extraction and processing
Getting started with reptiles (1): Learn the basics and skills of reptiles
Python object-oriented programming basics and sample code
MySQL database operation guide: learn how to use Python to add, delete, modify and query operations
Python file operation guide: encoding, reading, writing and exception handling
Selenium Automation Toolset - Complete Guide and Tutorials
Python web crawler basics advanced to actual combat tutorial
Pandas data processing and analysis tutorial: from basics to actual combat
Detailed explanation of commonly used data types and related operations in Python
[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model