[Python Newbie] Asked about importing nested packages
phpcn_u1582
phpcn_u1582 2017-06-30 09:54:57
0
2
723

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?

phpcn_u1582
phpcn_u1582

reply all (2)
大家讲道理

Although they are all sub-modules, their implementation logic is actually different, which leads to the fact that the final import must be aPythonfile, not a module directory, so the second codeThe import Sendmsgpart actually introduces this Python file, and the previousfrom Msgnew.Msgtells 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:

    __all__ = ["Sendmsg","Receivemsg"] from . import Sendmsg from . import Receivemsg

    As shown in the picture:

    The next time you execute it, it will be successful!

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!