In [69]: def fa(a=100,b,c=200):...:passFile"<ipython-input-69-d5678b64f352>",line1deffa(a=100,b,c=200):^SyntaxError:non-defaultargumentfollowsdefaultargument
而向函数传递参数也有两种方式,一种是不带关键字的传递,一种是带关键字的传递。
注意,非关键词参数的传递一定要在关键词参数传递之前。
举个错误的例子:
In [70]: def fa(a,b=100,c=200):...:pass...:In [71]: fa(a=100,30)File"<ipython-input-71-5a229b8e420e>",line1fa(a=100,30)^SyntaxError:positionalargumentfollowskeywordargument
defcheeseshop(kind,*arguments,**keywords):print("-- Do you have any",kind,"?")print("-- I'm sorry, we're all out of",kind)for arg inarguments:print(arg)print("-"*40)for kw inkeywords:print(kw,":",keywords[kw])
我们可以这样调用:
cheeseshop("Limburger","It's very runny, sir.","It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
将会得到下面的结果:
--DoyouhaveanyLimburger?--I'm sorry, we'realloutofLimburgerIt's very runny, sir.It'sreallyvery,VERYrunny,sir.----------------------------------------shopkeeper:MichaelPalinclient:JohnCleesesketch:CheeseShopSketch
>>>deff(ham:str,eggs:str='eggs') ->str:... print("Annotations:", f.__annotations__)... print("Arguments:", ham, eggs)... return ham +' and '+ eggs...>>>f('spam')Annotations:{'ham':<class'str'>,'return':<class'str'>,'eggs':<class'str'>}Arguments: spam eggs'spam and eggs'