函数 print_two 的问题是:它并不是创建函数最简单的方法。在 Python 函数中我们可以跳过整个参数解包的过程,直接使用 () 里边的名称作为变量名。这就是 print_two_again 实现的功能。
接下来的例子是 print_one ,它向你演示了函数如何接受单个参数。
最后一个例子是 print_none ,它向你演示了函数可以不接收任何参数。
1 # this one is like your scripts with argv 2 def print_two(*args): 3 arg1, arg2 = args 4 print "arg1: %r, arg2: %r" % (arg1, arg2) 5 6 # ok, that *args is actually pointless, we can just do this 7 def print_two_again(arg1, arg2): 8 print "arg1: %r, arg2: %r" % (arg1, arg2) 9 10 # this just takes one argument 11 def print_one(arg1): 12 print "arg1: %r" % arg1 13 14 # this one takes no arguments 15 def print_none(): 16 print "I got nothin'." 17 18 19 print_two("Zed","Shaw") 20 print_two_again("Zed","Shaw") 21 print_one("First!") 22 print_none() 23
*args 的 *是什么意思?它的功能是告诉 python 让它把函数的所有参数都接受进来,然后放到名字叫 args 的列表中去。和你一直在用的 argv 差不多,只不过前者是用在函数上面。没什么特殊情况,我们一般不会经常用到这个东西。
1 def cheese_and_crackers(cheese_count, boxes_of_crackers): 2 print "You have %d cheeses!" % cheese_count 3 print "You have %d boxes of crackers!" % boxes_of_crackers 4 print "Man that's enough for a party!" 5 print "Get a blanket.\n" 6 7 8 print "We can just give the function numbers directly:" 9 cheese_and_crackers(20, 30) 10 11 12 print "OR, we can use variables from our script:" 13 amount_of_cheese = 10 14 amount_of_crackers = 50 15 16 cheese_and_crackers(amount_of_cheese, amount_of_crackers) 17 18 19 print "We can even do math inside too:" 20 cheese_and_crackers(10 + 20, 5 + 6) 21 22 23 print "And we can combine the two, variables and math:" 24 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)