为什么python中的变量使用类似函数的语法,在变量名称前面加上()但实际上它们不是函数?
在python中定义变量的方式有多少为什么python中的变量使用类似函数的语法,在变量名称前面加上()但实际上它们不是函数?,python,tensorflow,keras,Python,Tensorflow,Keras,在python中定义变量的方式有多少 一个变量是否可以通过类似函数的符号调用另一个变量 例如: from tensorflow.keras import layers inputs = keras.Input(shape=(784,)) dense = layers.Dense(64, activation='relu') x = dense(inputs) 我的问题是,稠密是一个变量,它像函数一样将输入作为参数 一个变量在运行时可能有不同的类型,如int和函数,可以使用typ
from tensorflow.keras import layers
inputs = keras.Input(shape=(784,))
dense = layers.Dense(64, activation='relu')
x = dense(inputs)
我的问题是,稠密是一个变量,它像函数一样将输入作为参数
一个变量在运行时可能有不同的类型,如
int
和函数
,可以使用type()
内置函数进行检查
当变量的引用是可调用的时,它也可以像函数一样与()
一起使用,可以使用callable()
内置函数对其进行测试
此外,在Python中,函数可以返回另一个函数,类实例可以像函数一样被调用
下面是一个示例,首先我们定义3个简单函数:
def sum(a, b):
return a + b
def mul(a, b):
return a * b
def noop(a, b):
pass
然后我们定义一个函数,它接受一个参数并返回另一个函数:
def chooseOperation(sign):
operations = {"+": sum, "*": mul} # sum and mul are functions
return operations[sign] if sign in operations else noop # noop is a function
最后,我们声明一个接收函数调用结果的变量,该变量是对其中一个简单函数的引用
operation = chooseOperation("+") # returns sum
print(operation(2, 3)) # 5
operation = chooseOperation("*") # returns mul
print(operation(2, 3)) # 6
operation = chooseOperation("%") # returns noop
print(operation(2, 3)) # None
您可以使用类型(变量)
检查变量类型:
需要理解的重要部分是densed
变量引用类densed
的实例,该类是可调用的
。这就是允许您将()
与稠密变量一起使用的原因
TySoFraseAPI可能有点太难摄取,所以请考虑这个简单的例子:
class Dense():
def sum(self, a, b):
return a + b
def __call__(self, a, b): # Instances will now be callable
return self.sum(a, b)
dense = Dense() # Dense constructor, no args
print(type(dense)) # <class '__main__.Dense'>
sum = dense(1, 6) # 7 - Triggers __call__ which in turn calls sum(1, 6)
class():
定义和(自身、a、b):
返回a+b
定义调用(self,a,b):#实例现在可以调用
返回自和(a,b)
稠密=稠密()#稠密构造函数,无参数
打印(打印(密度))#
sum=稠密(1,6)#7-触发器uu调用uu,它反过来调用sum(1,6)
当一个类实现了\uuuu call\uuu
时,它的实例就变成了可调用的
,就像一个函数一样
由于更复杂的继承结构,它在TensorFlow API中的实现方式略有不同,但遵循相同的原则。Dense是一个函数而不是一个变量。您必须告诉它在该层中有多少完全连接的节点-它是参数。dense
是一个变量,该变量包含对函数的引用。您的问题没有明确提出一个特定的问题(标题中有一个问题,前两句是不同的问题,最后一行是另一个问题),但另一篇文章可能会澄清你的困惑:“x=densed(inputs)”这行用小写字母densed variable表示,输入在()括号内。densed是tf.keras.layers.densed@kaya3中的一个类。inputs和densed都是变量。
from tensorflow.keras import layers
dense = layers.Dense(64, activation='relu')
print(type(dense)) # <class 'tensorflow.python.keras.layers.core.Dense'>
print(callable(dense)) # True
class Dense():
def sum(self, a, b):
return a + b
def __call__(self, a, b): # Instances will now be callable
return self.sum(a, b)
dense = Dense() # Dense constructor, no args
print(type(dense)) # <class '__main__.Dense'>
sum = dense(1, 6) # 7 - Triggers __call__ which in turn calls sum(1, 6)