Use 'import module' or 'from module import'?

前端 未结 19 2163
一向
一向 2020-11-21 07:47

I\'ve tried to find a comprehensive guide on whether it is best to use import module or from module import. I\'ve just started with Python and I\'m

19条回答
  •  失恋的感觉
    2020-11-21 08:15

    This is my directory structure of my current directory:

    .  
    └─a  
       └─b  
         └─c
    
    1. The import statement remembers all intermediate names.
      These names have to be qualified:

      In[1]: import a.b.c
      
      In[2]: a
      Out[2]: 
      
      In[3]: a.b
      Out[3]: 
      
      In[4]: a.b.c
      Out[4]: 
      
    2. The from ... import ... statement remembers only the imported name.
      This name must not be qualified:

      In[1]: from a.b import c
      
      In[2]: a
      NameError: name 'a' is not defined
      
      In[2]: a.b
      NameError: name 'a' is not defined
      
      In[3]: a.b.c
      NameError: name 'a' is not defined
      
      In[4]: c
      Out[4]: 
      

    • Note: Of course, I restarted my Python console between steps 1 and 2.

提交回复
热议问题