写python一段时间了,但是对import和from import却没有深刻的认识。借由官方文档https://docs.python.org/2/tutorial/modules.html,和stackoverflow上的回答对这两个导入语句有了一些了解。
一. 两个概念:
1.module
A module is a file containing Python definitions and statements.
所以module就是一个.py文件
2.package
Packages 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;
……
所以package就是一个包含.py文件的文件夹,文件夹中还包含一个特殊文件__.init__.py
二. import和from import的用法
import package1 #✅
import module #✅
from module import function #✅
from package1 import module #✅
from package1.package2 import #✅
import module.function1 #❌
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.
Or in 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
is not defined, so X.name doesn’t work. And if name was already
defined, it is replaced by the new version. And if 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.