Python中函数调用的含义? [英] Meaning of function calling in Python?

查看:87
本文介绍了Python中函数调用的含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Keras的教程中看到了这样的Python函数调用方式:

I saw a Python function calling way in Keras' tutorial like this:

from keras.layers import Input, Dense
from keras.models import Model

# this returns a tensor
inputs = Input(shape=(784,))

# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)

但是,我不知道函数调用形式的含义是什么

However, I have no idea what is the meaning of the function calling form:

x = Dense(64, activation='relu')(inputs)

为什么函数"Dense"的参数列表的括号之外有(输入)"?

Why is there a "(inputs)" outside the bracket of the function "Dense"'s parameters list?

推荐答案

由于Dense(...)返回一个可调用对象(基本上是一个函数),因此可以依次调用它.这是一个简单的示例:

Because Dense(...) returns a callable (basically, a function), so it can be called in turn. Here's a simple example:

def make_adder(a):
    def the_adder(b):
        return a + b
    return the_adder

add_three = make_adder(3)
add_three(5)
# => 8

make_adder(3)(5)
# => 8

在这里,make_adder(3)返回定义为的函数

Here, make_adder(3) returns the function that is defined as

def the_adder(b)
    return 3 + b

然后使用参数5调用该函数将返回8.如果跳过将make_adder(3)的返回值分配给单独的变量的步骤,则会得到您所询问的形式:make_adder(3)(5)与问题中的Dense(64, activation='relu')(inputs)是同一件事.

then calling that function with argument 5 returns 8. If you skip the step of assigning the return value of make_adder(3) to a separate variable, you get the form that you were asking about: make_adder(3)(5) is the same thing as Dense(64, activation='relu')(inputs) from your question.

从技术上讲,Dense在Python中不是归类为函数,而是一个类.因此,Dense(...)是构造函数的调用.所讨论的类定义了__call__方法,该方法使此类的对象可调用".可以通过使用参数列表调用函数和可调用对象来调用它们,并且两者之间的差异完全不影响解释.但是,这是一个简单的可调用示例,它更类似于Dense:

Technically, Dense is not classified as a function in Python, but as a class; Dense(...) is thus an invocation of a constructor. The class in question defines the __call__ method, which makes objects of this class "callable". Both functions and callable objects can be called by invoking them with an argument list, and the difference between the two does not impact the explanation at all. However, here's an example of a simple callable, that more closely parallels Dense:

class Adder:
    def __init__(self, a):
        self.a = a
    def __call__(self, b):
        return self.a + b

adder_of_three = Adder(3)
adder_of_three(5)
# => 8

Adder(3)(5)
# => 8

这篇关于Python中函数调用的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆