【问题标题】:Passing arguments to function after parenthesis在括号后将参数传递给函数
【发布时间】:2020-09-12 20:09:42
【问题描述】:

我在 Python 中无法理解这段代码

x = layers.Flatten()(last_output)

既然Flatten是一个函数,那么函数如何从写在函数调用括号外的last_output获取数据。不记得在 Java 中看到过这种代码。

感谢和问候

【问题讨论】:

标签: python function tensorflow call


【解决方案1】:

Flatten() 是类实例化(您可能很清楚),第二个使用该参数调用实例。为此,该类必须定义一个 __call__ 函数。

例子:

class Sum:
    def __call__(self, a, b, c):
        return a + b + c

s = Sum()
print(s(3, 4, 5))
print(Sum()(3,4,5))

使用返回另一个带参数的函数的函数也可以获得相同的行为:

def Sum2():
    def Sum3(a, b, c):
        return a + b + c
    return Sum3

s2 = Sum2()
print(s2(3, 4, 5))
print(Sum2()(3, 4, 5))

【讨论】:

    【解决方案2】:

    考虑一下

    def outer():
        def print_thrice(string):
              for _ in range(3):
                  print (string)
        return print_thrice
    

    如果您调用outer,它将返回您可以调用的print_thrice 函数。所以你会像这样使用它

    x = outer()
    x("hello")
    

    或者更简洁,outer()("hello") 这就是这里发生的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多