1. 程式人生 > >python的模組和包機制:import和from..import..

python的模組和包機制:import和from..import..

一. 兩個概念:

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和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 doesnt have a name starting with_”)or what ever the name you mentioned.Orin other words, after youve 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 doesnt 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 wont notice.*This makes all names from the module available in the local namespace.