First look at the directory structure of my package:
The name of the outermost package is Msgnew, which contains an init file. There is a module called get and a sub-package called Msg. Enter the Msg sub-package and you can see that there is also an init file and there are 2 modules, one is called Sendmsg and the other is called Receivemsg module
I now want to import the Sendmsg module in the sub-package and use one of the functions
By the way, let me introduce the Sendmsg module, which is actually three functions, as shown in the figure:
The code for the import process is as follows:
# -*- coding:gb2312 -*-
# 代码1
from Msgnew import Msg
Msg.Sendmsg.test1()
# 代码2
#from Msgnew.Msg import Sendmsg
#Sendmsg.test1()
Here are code 1 and code 2
The execution results of code 1 are as follows:
Then comment out code 1 and then execute code 2. The result is as follows:
I don’t understand this very much,
Are the two pieces of code in the red box not equivalent?
In my opinion, these two should mean the same thing. Why is one wrong and the other right?
Although they are all sub-modules, their implementation logic is actually different, which leads to the fact that the final import must be a
Python
file, not a module directory, so the second codeThe import Sendmsg
part actually introduces this Python file, and the previousfrom Msgnew.Msg
tells the parser where to find the Sendmsg file.I know where the problem I encountered lies.
When importing is not a module but a package, if you want to directly import the modules inside together, you must write in the init file of the package:
As shown in the picture:
The next time you execute it, it will be successful!