繁体   English   中英

具有多个参数的函数** args

[英]function with multiple arguments **args

我正在学习python,这是从

http://www.learnpython.org/page/MultipleFunctionArguments

他们有一个示例代码不起作用-我想知道这只是一个错字还是根本不起作用。

def bar(first, second, third, **options):
    if options.get("action") == "sum":
        print "The sum is: %d" % (first + second + third)

    if options.get("return") == "first":
        return first

result = bar(1, 2, 3, action = "sum", return = "first")
print "Result: %d" % result

Learnpython认为输出应该是-

The sum is: 6
Result: 1

我得到的错误是-

Traceback (most recent call last):
  File "/base/data/home/apps/s~learnpythonjail/1.354953192642593048/main.py", line 99, in post
    exec(cmd, safe_globals)
  File "<string>", line 9
     result = bar(1, 2, 3, action = "sum", return = "first")
                                                ^
 SyntaxError: invalid syntax

有没有办法做他们想做的事,还是这个例子不对? 抱歉,我确实看过有人回答的python教程,但我不知道如何解决此问题。

return是python中的关键字-您不能将其用作变量名。 如果您将其更改为其他内容(例如ret ),它将正常工作。

def bar(first, second, third, **options):
    if options.get("action") == "sum":
        print "The sum is: %d" % (first + second + third)

    if options.get("ret") == "first":
        return first

result = bar(1, 2, 3, action = "sum", ret = "first")
print "Result: %d" % result

您可能不应使用“ return ”作为参数名称,因为它是Python命令。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM