Python basic tutorial and import from ... import

Import, and is generally used import ... Import from ... module.

In the following code within the file spam.py Example.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# spam.py
print('from the spam.py')

money = 1000

def read1():
    print('spam模块:', money)

def read2():
    print('spam模块')
    read1()

def change():
    global money
    money = 0

A, import the module name

# run.py
import spam  # from the spam.py
import spam

import import module for the first time three things happened:

  1. Create a module to module, whichever namespace
  2. Execution module corresponding file, will perform the namespace name generated in the process are thrown into the module
  3. Get a module name in the current executable file

Repeat the import module will directly create good results before drinking it, the file will not repeat the module, that is repeated import will happen: spam = spam = memory address space module name

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# run.py
import spam as sm

money = 111111

sm.money
sm.read1()  # 'spam模块:1000'
sm.read2
sm.change()

print(money)  # 1000

Introducing a plurality of modules

import spam, time, os

# 推荐使用下述方式
import spam
import time
import os

Two, from the module name import specific functions

# run.py

from spam import money

money = 10

print(money)  # 10

from ... import ... first import module happened three things:

  1. Create a module to module, whichever namespace
  2. Execution module corresponding file, will perform the namespace name generated in the process are thrown into the module
  3. Get a name in the current namespace executable file, the name of the module directly to a particular name, which means you can not add any prefix directly
  • Pros: do not add a prefix code more streamlined
  • Disadvantages: easily conflict with the currently executing file namespace name

Import all functions within the file:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# spam.py

__all__ = ['money', 'read1']  # 只允许导入'money'和'read1'
# run.py
from spam import *  # 导入spam.py内的所有功能,但会受限制于__all__

Three, import and similarities and differences from ... import ...

Same point:

  1. Both modules will execute the corresponding file, the two modules will have a namespace
  2. When both calling function to find the scope of the relationship, and calls need to go to define the position has nothing to do

difference

  1. import need to add the prefix; from ... import ... no need to add the prefix

Guess you like

Origin blog.51cto.com/14246112/2430442