函数参数的默认值等于另一个参数 [英] Function argument's default value equal to another argument

查看:27
本文介绍了函数参数的默认值等于另一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将函数参数的默认值定义为同一函数定义中的另一个参数?类似的东西:

Is it possible to define a function argument's default value to another argument in the same function definition? Something like:

def func(a, b=a):
  print a, b

但这没有用.

推荐答案

没有.这不可能.当没有全局变量 a 时,Python 解释器认为你想将参数 b 的默认值赋给一个全局变量 a.

No. This is not possible. The Python interpreter thinks that you want to assign the default value of argument b to a global variable a when there isn't a global variable a.

您可能想尝试这样的事情:

You might want to try something like this:

def func(a, b=None):
    if b is None:
        b = a

这篇关于函数参数的默认值等于另一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆