在建筑物图表标题下的此链接中,有一行说
"Python 库中的 ops 构造函数返回代表构造操作输出的对象。您可以将这些传递给其他操作构造函数以用作输入。
构造函数这个词是什么意思?是在面向对象编程的上下文中还是在组装图形的上下文中?
实际上介于两者之间。"Ops 构造函数"是指创建对象作为 Ops 的新实例的函数。例如,tf.constant
构造一个新的操作,但实际上返回了对张量的引用,这是此操作的结果,即tensorflow.python.framework.ops.Tensor
的实例,但它不是OOP意义上的构造函数。
特别是具有实际逻辑的东西,例如tf.add
将创建tensorflow.python.framework.ops.Operation
(执行加法)和tensorflow.python.framework.ops.Tensor
(存储操作结果),并且只会返回张量(这是文档引用部分试图解释的内容)。
例如:
import tensorflow as tf
tensor = tf.add(tf.constant(1), tf.constant(2))
for op in tf.get_default_graph().get_operations():
print op
print tensor
将导致
name: "Const"
op: "Const"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 1
}
}
}
name: "Const_1"
op: "Const"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 2
}
}
}
name: "Add"
op: "Add"
input: "Const"
input: "Const_1"
attr {
key: "T"
value {
type: DT_INT32
}
}
Tensor("Add:0", shape=TensorShape([]), dtype=int32)
已经"在后台"创建了三个操作,而您仍在张量级别(已由tf.add
返回)。它的名称(默认创建)表明它是Add
操作产生的张量。
更新
一个简单的基于 python 的示例可能更有用,因此 TF 会做这样的事情:
class B:
def __init__(self):
print 'Constructor of class B is called'
pass
class A:
def __init__(self):
print 'Constructor of class A is called'
self.b = B()
def create_something():
print 'Function is called'
a = A()
b = a.b
print 'Function is ready to return'
return b
print create_something()
如您所见create_something
不是构造函数,它调用某些类的构造函数并返回某个实例,但本身不是 OOP 意义上的构造函数(也不是初始值设定项)。它更像是一个工厂设计的paradim。