码迷,mamicode.com
首页 > 编程语言 > 详细

Python之import

时间:2015-03-13 01:39:25      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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.pi
3.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
>>> pi
3.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

标签:

原文地址:http://www.cnblogs.com/mengdie/p/4334101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!