Import imports: such as import ModuleName
Variable name Modulenmae has two purposes: identify the external file to be loaded at the same time generate a variable in the script, after the file is loaded, to refer to the module object; Because import makes a variable name refer to the entire module object, we have to get the module's properties through the module name
From statement:
From will assign the variable name within the module to another scope (the variable name in the module and the copy selected in the FROM clause to the scope of the import), so it allows us to use the copied variable directly in the script without passing the module
By default, Python does only one operation per process for each file, and then only the module objects that have been loaded are removed
both import and from are invisible assignment statements
- Import assigns the entire module object to a variable name (modulename)
- From assigning one or more variable names to an object of the same name in another module
The from has the potential to destroy namespaces, and if you use from to import variables, and those variables happen to have the same name as the variables in action, the variables will be silently overwritten.
You must use the import when you must use a variable with the same variable name defined within two different modules
Use:
"" "test.py" ""
Key= ' Got '
Print {' already ': (lambda:2+2),
' Got ':(lambda:2*4),
' One ': (lambda:2**4)
}[key] ()
def printer (data):
Print (data)
#主程序
From test import Key,printer
Print key
Printer (key)
Import Test
Print Test.key
Test.printer (Test.key)
module load and scope:
- Module statements are executed on first import
- The top-level assignment statement creates module properties: Statements that assign variables at the top of the file (not within Def and Class) when the module is imported, create the properties of the module object, and the assigned variable name is stored in the module's namespace
- The namespace of the module can be obtained through the attribute __dict__ or dir (M): The namespace of the module created by the import is a dictionary
- A module is a separate scope (a local variable is a global variable): In a module, the module scope becomes the module object's attribute dictionary after the module is loaded, and the scope of the module file becomes the namespace of the module object's properties after the import.
Python Import and From.........import module loading and scoping