python import導入模塊

  • regular imports 常規導入
  • use from to import relative imports 相對導入
  • optional imports 可選導入
  • local imports 本地導入
  • import considerations 導入注意事項

regular imports:

import sys, time

use from to import:

If you just want to import part of some module:

from mock import Mock, patch

relative import:

my_package/
    __init__.py
    subpackage1/
        __init__.py
        module_x.py
        module_y.py
    subpackage2/
        __init__.py
        module_z.py
    module_a.py

in __init__.py (/my_package) 
from . import subpackage1
from . import subpackage2

in __init__.py (/my_package/subpackage1)
from . import module_x
from . import module_y

in module_x.py
from .module_y import spam as ham

optional import:

try:
    # For Python 3
    from http.client import responses
except ImportError:  # For Python 2.5-2.7
    try:
        from httplib import responses  # NOQA
    except ImportError:  # For Python 2.4
        from BaseHTTPServer import BaseHTTPRequestHandler as _BHRH
        responses = dict([(k, v[0]) for k, v in _BHRH.responses.items()])

可選導入的使用很常見,是一個值得掌握的技巧

Local import:

import sys  # global scope

def square_root(a):
    # This import is into the square_root functions local scope
    import math
    return math.sqrt(a)

def my_pow(base_num, power):
    return math.pow(base_num, power)

if __name__ == '__main__':
    print(square_root(49))
    print(my_pow(2, 3))

import considerations:

  • 循環導入(circular imports)
# a.py
import b

def a_test():
    print("in a_test")
    b.b_test()
a_test()
import a

def b_test():
    print('In test_b"')
    a.a_test()

b_test()
  • 覆蓋導入(Shadowed imports,暫時翻譯爲覆蓋導入)

當你創建的模塊與標準庫中的模塊同名時,如果你導入這個模塊,就會出現覆蓋導入。舉個例子,創建一個名叫 math.py 的文件,在其中寫入如下代碼:

import math

def square_root(number):
    return math.sqrt(number)

square_root(72)
PEP 302中介紹了導入鉤子**(import hooks),支持實現一些非常酷的功能,比如說直接從github導入。Python標準庫中還有一個importlib**模塊,值得查看學習。當然,你還可以多看看別人寫的代碼,不斷挖掘更多好用的妙招。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章