简体   繁体   English

用可选参数定义函数

[英]defining functions with optional arguments

Hi I'm trying to understand how to implement optional arguments in a python function. 嗨,我试图了解如何在python函数中实现可选参数。 For example, in the basic function below 例如,在下面的基本功能中

def Ham(p,*q):
    if q:
        print p+q
    else:
        print p

Ham(2)


Ham(2,3)

I expect Ham(2) to return '2' which it does, however Ham(2,3) gives an error. 我希望Ham(2)会返回'2',但是Ham(2,3)会给出错误。

EDIT: Many thanks. 编辑:非常感谢。 Many of your answers were useful. 您的许多答案很有用。

In your particular example, I think you mean to do: 在您的特定示例中,我认为您的意思是:

def Ham(p,q=None):
    if q:
        print p+q
    else:
        print p

That is, give q a default value of None and then only calculate p+q if a q is provided. 也就是说,给q的一个默认值None ,然后才计算p+q ,如果q被提供。 Even simpler would be: 更简单的是:

def Ham(p,q=0):
    print p+q

Using *q you are specifyng a list of arguments not known until runtime and python expecting q to be a tuple, it means you can call Ham like below: 使用* q可以指定运行时之前未知的参数列表,而python则期望q是一个元组,这意味着您可以像下面这样调用Ham:

Ham(1, 2) # q = (2,)
Ham(1, 2, 3) # q = (2, 3)
Ham(1, 2, 3, 4) # q = (2, 3, 4)

Insidia of Ham function you have to treat q as a tuple, I mean, q[0] rather than q. Ham函数的惯性,您必须将q视为元组,我的意思是q [0]而不是q。 You can have a look to this link to have a better idea. 您可以查看此链接以获得更好的主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM