python导入函数模块 为什么会打印两次_python – 为什么从模块导入函数比从整个模块本身需要更长时间?...

那是因为:

from win32com.client import Dispatch

等效于:

import win32com.client #import the whole module first

Dispatch = win32com.client.Dispatch #assign the required attributes to global variables

del win32com #remove the reference to module object

但是从win32com.client导入Dispatch有它自己的优点,例如,如果你在代码中多次使用win32com.client.Dispatch,那么最好将它分配给一个变量,这样可以减少查找次数。否则每次调用win32com.client.Dispatch()将首先搜索搜索win32com然后客户端在win32com内,最后在Win32com.client内部调度。

字节码比较:

从字节代码,很明显,从os.path import splitext所需的步骤数量大于简单导入。

>>> def func1():

from os.path import splitext

...

>>> def func2():

import os.path

...

>>> import dis

>>> dis.dis(func1)

2 0 LOAD_CONST 1 (-1)

3 LOAD_CONST 2 (('splitext',))

6 IMPORT_NAME 0 (os.path)

9 IMPORT_FROM 1 (splitext)

12 STORE_FAST 0 (splitext)

15 POP_TOP

16 LOAD_CONST 0 (None)

19 RETURN_VALUE

>>> dis.dis(func2)

2 0 LOAD_CONST 1 (-1)

3 LOAD_CONST 0 (None)

6 IMPORT_NAME 0 (os.path)

9 STORE_FAST 0 (os)

12 LOAD_CONST 0 (None)

15 RETURN_VALUE

模块缓存:

注意,从os.path import splitext以后,你仍然可以使用sys.modules访问os模块,因为python缓存导入的模块。

Note For efficiency reasons, each module is only imported once per

interpreter session. Therefore, if you change your modules, you must

restart the interpreter – or, if it’s just one module you want to test

interactively, use reload(), e.g. reload(modulename).

演示:

import sys

from os.path import splitext

try:

print os

except NameError:

print "os not found"

try:

print os.path

except NameError:

print "os.path is not found"

print sys.modules['os']

输出:

os not found

os.path is not found

时序比较:

$ python -m timeit -n 1 'from os.path import splitext'

1 loops, best of 3: 5.01 usec per loop

$ python -m timeit -n 1 'import os.path'

1 loops, best of 3: 4.05 usec per loop

$ python -m timeit -n 1 'from os import path'

1 loops, best of 3: 5.01 usec per loop

$ python -m timeit -n 1 'import os'

1 loops, best of 3: 2.86 usec per loop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值