您的位置:首页 > 编程语言 > Python开发

python的模块和包机制:import和from..import..

2016-12-21 17:23 656 查看
写python一段时间了,但是对import和from import却没有深刻的认识。借由官方文档https://docs.python.org/2/tutorial/modules.html,和stackoverflow上的回答对这两个导入语句有了一些了解。一. 两个概念:1.moduleA module is a file containing Python definitions and statements. 所以module就是一个.py文件2.packagePackages 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和from import的含义来自stackoverflowimport 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 objectsdefined by that module in the current namespace (that is, everythingthat doesn’t have a name starting with “_”) or what ever the nameyou mentioned.Or in other words, after you’ve run this statement, you can simplyuse a plain name to refer to things defined in module X. But X itselfis not defined, so X.name doesn’t work. And if name was alreadydefined, it is replaced by the new version. And if name in X ischanged to point to some other object, your module won’t notice.* This makes all names from the module available in the local namespace.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: