This question already has answers here:
Asterisk in function call [duplicate]

(3个答案)



proper name for python * operator?

(8个答案)


7年前关闭。




在Peter Norvig用Python(http://norvig.com/lispy.html)编写的Lisp解释器中,他对Lisp的eval的定义如下:
def eval(x, env=global_env):
    "Evaluate an expression in an environment."
    if isa(x, Symbol):             # variable reference
        return env.find(x)[x]
    elif not isa(x, list):         # constant literal
        return x
    elif x[0] == 'quote':          # (quote exp)
        (_, exp) = x
        return exp
    elif x[0] == 'if':             # (if test conseq alt)
        (_, test, conseq, alt) = x
        return eval((conseq if eval(test, env) else alt), env)
    elif x[0] == 'set!':           # (set! var exp)
        (_, var, exp) = x
        env.find(var)[var] = eval(exp, env)
    elif x[0] == 'define':         # (define var exp)
        (_, var, exp) = x
        env[var] = eval(exp, env)
    elif x[0] == 'lambda':         # (lambda (var*) exp)
        (_, vars, exp) = x
        return lambda *args: eval(exp, Env(vars, args, env))
    elif x[0] == 'begin':          # (begin exp*)
        for exp in x[1:]:
            val = eval(exp, env)
        return val
    else:                          # (proc exp*)
        exps = [eval(exp, env) for exp in x]
        proc = exps.pop(0)
        return proc(*exps)

isa = isinstance

Symbol = str

这行使我特别感兴趣:
return proc(*exps)
exps中的星号到底在做什么?

最佳答案

单个星号先放入可排序对象,然后再对其进行拆包,如Joran所示:

In [1]: def f(*args): return args

In [2]: f(1,2,3)
Out[2]: (1, 2, 3)

In [3]: f(*[1,2,3,4])
Out[3]: (1, 2, 3, 4)

(请注意*的第三个应用程序:在函数定义中,星号表示可变长度的参数列表,所有参数都打包在args中的一个列表In [1]中)

另外值得注意的是,双星号(**)执行字典解包:
In [5]: def g(foo=None, bar=42): return foo,bar

In [6]: g()
Out[6]: (None, 42)

In [7]: g(*[1,2])
Out[7]: (1, 2)

In [8]: g(**{'foo': 'FOO', 'bar': 'BAR'})
Out[8]: ('FOO', 'BAR')

关于python - 星号在Python中除了乘法和乘幂运算还有什么作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16515443/

10-12 18:41