为什么tf.Variable是可迭代的但不能迭代

时间:2016-10-01 13:44:13

标签: python python-2.7 tensorflow iterable

为什么会这样:

from collections import Iterable
import tensorflow as tf

v = tf.Variable(1.0)
print(isinstance(v, Iterable))

True

虽然这个

iter(v)

给出

TypeError: 'Variable' object is not iterable.

1 个答案:

答案 0 :(得分:6)

我在Tensorflow的Variable类中找到了以下方法:

def __iter__(self):
    """Dummy method to prevent iteration. Do not call.
    NOTE(mrry): If we register __getitem__ as an overloaded operator,
    Python will valiantly attempt to iterate over the variable's Tensor from 0
    to infinity.  Declaring this method prevents this unintended behavior.
    Raises:
      TypeError: when invoked.
    """
    raise TypeError("'Variable' object is not iterable.")

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/variables.py#L366