Python import用法以及與from...import的區別

來源:互聯網
上載者:User

Python import用法以及與from...import的區別

   這篇文章主要介紹了Python import用法以及與from...import的區別,本文簡潔明了,很容易看懂,需要的朋友可以參考下

  在python用import或者from...import來匯入相應的模組。模組其實就是一些函數和類的集合檔案,它能實現一些相應的功能,當我們需要使用這些功能的時候,直接把相應的模組匯入到我們的程式中,我們就可以使用了。這類似於C語言中的include標頭檔,Python中我們用import匯入我們需要的模組。

  eg:

   代碼如下:

  import sys

  print('================Python import mode==========================');

  print ('The command line arguments are:')

  for i in sys.argv:

  print (i)

  print ('\n The python path',sys.path)

  from sys import argv,path # 匯入特定的成員

  print('================python from import===================================')

  print('path:',path) # 因為已經匯入path成員,所以此處引用時不需要加sys.path

  如果你要使用所有sys模組使用的名字,你可以這樣:

   代碼如下:

  from sys import *

  print('path:',path)

  從以上我們可以簡單看出:

  ############################

  #匯入modules,import與from...import的不同之處在於,簡單說:

  # 如果你想在程式中用argv代表sys.argv,

  # 則可使用:from sys import argv

  # 一般說來,應該避免使用from..import而使用import語句,

  # 因為這樣可以使你的程式更加易讀,也可以避免名稱的衝突

  ###########################

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.