【问题标题】:Concatenation of strings in a default argument默认参数中的字符串连接
【发布时间】:2012-04-11 18:13:35
【问题描述】:

这是我的一段代码...

def contactMaster(data="",url= str(chosenMaster)+"todolist"):
    print "url: "+url

它只打印“todolist”而不是“http://www.mysite.com/blah/1234/todolist”

为什么它不起作用??

【问题讨论】:

  • 你怎么称呼它,什么叫法师?如果 selectedMaster 为空,则应打印 url: todolist。请给出一个完整的例子。

标签: python string concatenation default-arguments


【解决方案1】:

默认参数是在函数定义时计算,而不是在执行时计算。因此,如果在 Python 定义 contactMasterchosenMaster 为空,它将只打印 todolist

您需要将str(chosenMaster) 移动到函数中。

有关更多信息,请参阅 Python 教程中的 Default Argument Values。那里的例子是:

默认值在定义范围内的函数定义点进行评估,因此

i = 5

def f(arg=i):
    print arg

i = 6
f()

将打印5

【讨论】:

  • 是否可以在python中声明但不能初始化全局变量?在示例中,为了让它打印 6,我是否必须让 i=6,然后打印 i?
  • @spatara 不。为了让它打印6,你要么必须让它是6 before函数definition(这里是 5)或将 i 的计算移到函数体中,这将在 i 设置为 6 之后执行。跨度>
  • 是的!明白了,我的程序可以工作了......我在声明它时给了它我想要的值:)
【解决方案2】:

函数定义在函数声明时捕获chosenMaster的值,而不是在调用函数时

改为这样做:

def contactMaster(data='', url=None):
    if url is None:
        url = str(chosenMaster) + 'todolist'
    print 'url: ' + url

【讨论】:

    【解决方案3】:

    因为default function arguments are determined when the function is defined。事后更改chosenMaster 将无效。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2018-05-22
      • 2017-03-11
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多