开发者

pointer in python?

When I was trying to figure out the use of imp开发者_如何转开发.load_module in Python, I got the following code (origin page). It's my first time seeing the use of * in Python, is that some pointer like things?

thanks in advance

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


The * on front if info causes the list / tuple to be unwrapped into individual arguments to the function. You can read more about unpacking here in the python documentation. this can also be done with dictionaries for named arguments, see here

For example,

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)

Output:

1 2 3 4

EDIT:

According to comments to your question by jcomeau_ictx, the operator is called splat


I'm assuming you're talking about the _client = imp.load_module(modname, *info) line.

No, it's not a pointer. It expands the list passed in as an argument. Here's an example:

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

There's similar expansion possible for dictionaries.

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

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


Essentially, they are variables that hold the memory address of another variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜