python的模組和包機制:import和from..import..
阿新 • • 發佈:2019-01-03
一. 兩個概念:
1.module
A module is a file containing Python definitions and statements.
所以module就是一個.py檔案
2.package
所以package就是一個包含.py檔案的資料夾,資料夾中還包含一個特殊檔案__.init__.pyPackages are a way of structuring Python’s module namespace by using “dotted module names” …… The __init__.py files are required to make Python treat the directories as containing packages; ……
二. import和from import的用法
import package1 #✅
import module #✅
from module import function #✅
from package1 import module #✅
from package1.package2 import #✅
import module.function1 #❌
三. import和from import的含義
import X :
imports the module X ,and creates a reference to that module in the current
namespace.Then you need to define completed module path to access a
particular attribute or method from inside the module.
from X import * :
*imports the module X,and creates references to all public objects
defined by that module in the current namespace (that is, everything
that doesn’t have a name starting with“_”)or what ever the name
you mentioned.Orin other words, after you’ve run this statement, you can simply
use a plain name to refer to things defined in module X.But X itself
isnot defined, so X.name doesn’t work.Andif name was already
defined, it is replaced by the new version.Andif name in X is
changed to point to some other object, your module won’t notice.*This makes all names from the module available in the local namespace.