括号后将参数传递给函数

问题描述 投票:0回答:2

我在使用Python理解此代码时遇到问题

x = layers.Flatten()(last_output)

由于Flatten是一个函数,所以该函数如何从写在函数调用括号之外的last_output获取数据。不记得在Java中看到过这种代码。

感谢和问候

python function tensorflow call
2个回答
0
投票
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))


0
投票
考虑此

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

如果调用outer,它将返回您可以调用的print_thrice功能。因此,您可以像这样使用它

x = outer() x("hello")

或更简洁地说,outer()("hello")这就是这里的情况。 
© www.soinside.com 2019 - 2024. All rights reserved.