默认参数不起作用

时间:2015-04-24 09:33:45

标签: python

我在Python代码中遇到了以下问题。

错误是:

Traceback (most recent call last): File "cmd.py", line 16, in <module>
    func(b="{cmd} is entered ...") # Error here
File "cmd.py", line 5, in func
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr)
KeyError: 'cmd'

代码:

import re

def func(errStr = "A string", b = "{errStr}\n{debugStr}"):
    debugStr = "Debug string"
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr)
    raise ValueError(exceptMsg)

try:
    '''
    Case 1: If user invokes func() like below, error produced.
    Possible explanation: Paramter b of func() is looking keyword   
    'errStr' further down in func() body, but I am passing it keyword
    'cmd' instead. What to change to make the code work?
    '''
    #cmd = "A crazy string"             # Comment, make code pass 
    #func(b="{cmd} is entered ...")     # Error here

    # Case 2: If user invokes func() like below, OK.
    errStr = "A crazy string"
    func(b="{errStr} is entered")

except ValueError as e:
    err_msg_match = re.search('A string is entered:', e.message)
    print "Exception discovered and caught!"

1)如果保留了函数接口func(),需要更改哪些代码?

2)如果我必须修改功能界面,我该如何进行干净的代码更改?

1 个答案:

答案 0 :(得分:3)

b.format(errStr=errStr, debugStr=debugStr)仅传递errStrdebugStr来替换占位符。如果b包含任何其他占位符变量,则会失败。

你有:

b = "{cmd} is entered ..."

无法匹配{cmd}

如果您想将cmd传递给func,可以使用keyword arguments执行此操作:

def func(errStr = "A string", b = "{errStr}\n{debugStr}", **kwargs):
    debugStr = "Debug string"
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr, **kwargs)
    raise ValueError(exceptMsg)

并用作:

func(b="{cmd} is entered ...", cmd="A crazy string")