这实际上介于两者之间。 “Ops 构造函数”是指创建 Ops 对象的新实例的函数。例如 tf.constant 构造了一个新的操作,但实际上返回了对 Tensor 的引用作为该操作的结果,即 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)
“在后台”创建了三个操作,而您仍然在 Tensor 级别上进行操作(由 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 意义上的构造函数(也不是初始化程序)。它更像是工厂设计范式。