2011-06-07 83 views
2

当我试图找出在Python中使用imp.load_module时,我得到以下代码(origin page)。这是我第一次看到在Python中使用*,是否像某些指针一样?python中的指针?

由于在前面提前

import imp 
import dbgp 
info = imp.find_module(modname, dbgp.__path__) 
_client = imp.load_module(modname, *info) 
sys.modules["_client"] = _client 
from _client import * 
del sys.modules["_client"], info, _client 
+3

运营商被称为“splat”。这真的很难谷歌“*”,我知道:^) – 2011-06-07 15:26:45

+0

@jcomeau_ictx:多么可怕的一个不具名的名字 – GWW 2011-06-07 15:35:17

+0

我认为“星号”是更正式的名称。不过,我喜欢“splat”。 – 2011-06-07 15:37:00

回答

7

*如果info导致列表/元组被拆开成单独的函数的自变量。你可以在Python文档中阅读更多关于解包here的信息。这也可以用字典对于命名参数做,看到here

例如,

def do_something(a,b,c,d): 
    print("{0} {1} {2} {3}".format(a,b,c,d)) 

a = [1,2,3,4] 
do_something(*a) 

输出:

1 2 3 4 

编辑:

根据意见,由jcomeau_ictx你的问题,该运营商被称为splat

4

我假设你在谈论_client = imp.load_module(modname, *info)系列。

不,它不是指针。它扩展了作为参数传入的列表。这里有一个例子:

In [7]: def foo(bar, baz): 
    ...:  return bar + baz 
    ...: 

In [8]: l = [1,2] 

In [9]: foo(l) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 

/home/Daenyth/<ipython console> in <module>() 

TypeError: foo() takes exactly 2 arguments (1 given) 

In [10]: foo(*l) 
Out[10]: 3 

字典也有类似的扩展。

In [12]: d = {'bar': 1, 'baz': 2} 

In [13]: foo(**d) 
Out[13]: 3