【问题标题】:Python - Pass default values for arguments that are function of other arguments of the functionPython - 传递作为函数其他参数的函数的参数的默认值
【发布时间】:2018-12-03 02:58:42
【问题描述】:

我想编写一个函数,其中一个参数的默认值是传递给同一函数的一些参数的函数。像这样的:

def function(x, y = function2(x)):
    ##definition of the function

是否可以在 Python 中编写这样的函数? 我遇到了this c++ 的答案。但是Python中没有方法重载

提前致谢。

【问题讨论】:

    标签: python function arguments


    【解决方案1】:

    解决此问题的一种非常常用的方法是使用None 作为占位符:

    def function(x, y=None):
        if y is None:
            y = f2(x)
    
        pass  # whatever function() needs to do
    

    【讨论】:

    • 另外,这将是为某些 mutabe 类型变量设置默认值的最佳方式。
    【解决方案2】:

    这毫无意义。你想达到什么目标? Y是什么?是函数吗?那么你必须写:

    def function(x, y = function2):
        ##definition of the function
    

    如果 Y 是一个简单的值,那么你必须写:

    def function(x, y = None):
        if y is None:
             y = function2(x)
    

    【讨论】:

      【解决方案3】:

      我不知道你究竟想在这里实现什么用例,但你可以使用装饰器来满足你的需求。

      这里有一个愚蠢的例子https://repl.it/@SiddharthShishu/IntrepidPunctualProspect

      【讨论】:

        【解决方案4】:
        def function(x, y=None):
            if y is None:
                y = f2(x)
        

        【讨论】:

        • 请记住,如果诸如零、空集合和其他评估为 False 的值不是 y 的有效值,这将起作用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-21
        • 2019-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-30
        相关资源
        最近更新 更多