python基礎知識——包

來源:互聯網
上載者:User

標籤:tree   基礎   cto   print   file   ast   env   most   沒有   

包是一種通過使用“模組名”來組織python模組的名稱空間的方式。

無論是import形式還是from...import形式,凡是在匯入語句中(不是在使用時)遇到帶點的,就需要意識到——這是包。

包是目錄級的,檔案夾是用來組成py檔案(包的本質就是一個包含__init__.py檔案的目錄)。

import匯入檔案時,產生名稱空間中的名字來源於檔案,import包,產生的名稱空間的名字同樣來源於檔案,即包下的__init__.py,匯入包本質就是在匯入該檔案。

在python3中,即使包下沒有__init__.py檔案,import包仍然不會報錯,而在python2中,包下一定要有該檔案,否則import包報錯。

[[email protected] module]# tree.├── bonf  #包│?? ├── __pycache__│?? │?? └── test1.cpython-36.pyc  #匯入的時候產生的快取檔案│?? └── test1.py 模組└── conf   #包    ├── __pycache__    │?? ├── test2.cpython-36.pyc    │?? └── test1.cpython-36.pyc    ├── test2.py   #模組    └── test.py  #模組4 directories, 6 files#包中的內容#!/usr/bin/env pythondef func1():      #bonf包下模組test1中有個func1函數    print("bonf")                                                               ~                                                                       "bonf/test1.py" 3L, 50C    #另一個包conf#!/usr/bin/env pythondef func1():    #包conf下模組test1下函數func1    print("函數1")                                                            ~                                                                       "conf/test1.py" 3L, 53C      

現在來匯入這兩個包

>>> import bonf.test1>>> import conf.test1  #沒有報錯

現在來引用其中的函數

>>> bonf.test1.func1()bonf>>> conf.test1.func1()  #沒有毛病函數1

我們可以看到,兩個包下有同名的模組也不會衝突,它們來自各自的命名空間。

也是可以使用from-import,但是這樣會覆蓋命名空間。

>>> from conf import test1>>> test1.func1()函數1>>> from bonf import test1>>> test1.func1()bonf

多層也是可以的

>>> import bonf.donf.test10>>> donf.test10.func()   #少一層都不行,路徑要對Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name ‘donf‘ is not defined>>> bonf.donf.test10.func()2層

相對匯入和絕對匯入

>>> from bonf import test1  #絕對>>> from . import test1    #相對

 

python基礎知識——包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.