Python之import

來源:互聯網
上載者:User

標籤:

1  Import

    When program grows bigger, it‘s good to break it into different modules. A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py.

    Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword. For example, we can import the math module by typing in import math

>>> import math>>> math.pi3.141592653589793

  Now all the definitions inside math module are available. We can also import some specific attributes and functions only, using the from keyword.
  For example:

>>> from math import pi>>> pi3.141592653589793
   While importing a module, Python looks at several places defined in sys.path. It is a list of directory locations.
>>> import sys>>> sys.path[‘‘,  ‘C:\\Python33\\Lib\\idlelib‘,  ‘C:\\Windows\\system32\\python33.zip‘,  ‘C:\\Python33\\DLLs‘,  ‘C:\\Python33\\lib‘,  ‘C:\\Python33‘,  ‘C:\\Python33\\lib\\site-packages‘]
 We can add our own location to this list as well.

 

2  Ways to Import a Module

  Python provides at least three different ways to import modules. 

 

  • import X  imports the module X, and creates a reference to that module in the current namespace. In other words, after you’ve run this statement, you can use X.name to refer to things defined in module X.

  • from X import *  imports the module X, and creates references in the current namespace to all public objects defined by that module (that is, everything that doesn’t have a name starting with “_”). In other words, after you’ve run this statement, you can simply use a plain nameto 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.

  • from X import a, b, c  imports the module X, and creates references in the current namespace to the given objects. In other words, you can now use a and b and c in your program.

  • Finally, X = __import__(‘X’) works like import X, with the difference that you 1) pass the module name as a string, and 2) explicitly assign it to a variable in your current namespace.

 

Python之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.