【问题标题】:Is it possible to define a function with more than one set amount of parameters in Python? [duplicate]是否可以在 Python 中定义具有多个参数的函数? [复制]
【发布时间】:2016-01-21 00:19:50
【问题描述】:

我想定义一个带有两个参数的函数,可能还有第三个。 我相当肯定这是不可能的,但考虑到内置的 range 函数有:

range(stop) -> range object
range(start, stop[, step]) -> range object

也许有可能?或者我有错误的想法,因为range 实际上是一个不可变的序列类型?

为了清楚起见,example(x,y) 可以像 example(x,y,z) 一样运行相同的函数

【问题讨论】:

  • “我很确定这是不可能的”——你试过阅读official tutorial's section on defining functions吗?我很好奇你实际做了多少研究。
  • 通过堆栈交换和零教程阅读大约 6 分钟。
  • 虽然我不得不承认,我并没有考虑在搜索时使用关键字“可选”。完全是我的错。

标签: python function parameters arguments


【解决方案1】:
def example(x, y, z=None):
    if z is None:
        return x + y
    else:
        return x + y + z

然后

>>> example(3, 4)
7

>>> example(3, 4, 5)
12

【讨论】:

  • 就是这样!谢谢
【解决方案2】:

这可以通过default 参数(有时称为keyword 参数)实现...

def example(x, y, z=None):
    ...

在函数中,您将检查 z is None 是否已提供。

你也可以在这里使用*args

def example(x, y, *args):
    ...  # *args is a tuple of all of the rest of the positional arguments.

在这里,您可以使用len(args) 来确定是否传递了第三个参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-08
    • 2013-09-13
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2021-09-10
    相关资源
    最近更新 更多