Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 很难理解返回空列表的函数的行为_Python_List_Attributes_Iterator_Typeerror - Fatal编程技术网

Python 很难理解返回空列表的函数的行为

Python 很难理解返回空列表的函数的行为,python,list,attributes,iterator,typeerror,Python,List,Attributes,Iterator,Typeerror,我正在使用一些代码,这些代码使用了一个属性,下面的例子是我与我的解释器演示的最好的例子。我很难理解为什么代码会这样工作 In [377]: def a(): .....: return [] .....: 首先,我定义了一个简单的函数,它将返回一个空列表 In [381]: a() Out[381]: [] 接下来,我迭代此函数以尝试打印: In [397]: for i in a(): .....: print a.hello .....:

我正在使用一些代码,这些代码使用了一个属性,下面的例子是我与我的解释器演示的最好的例子。我很难理解为什么代码会这样工作

In [377]: def a():
   .....:     return []
   .....: 
首先,我定义了一个简单的函数,它将返回一个空列表

In [381]: a()
Out[381]: []
接下来,我迭代此函数以尝试打印:

In [397]: for i in a():
   .....:     print a.hello
   .....:     print a.hello()
   .....:     

In [398]: 
我没有得到任何输出。我注意到,我在执行
for
循环时得到了完全相同的结果,当时我返回了
元组,而不是
列表

In [399]: def a():
   .....:     return ()
   .....: 
在我看来,这似乎与
列表和
元组是空的有关。然而,真正令人困惑的是,当我调用
a
上的
hello
属性作为
for
循环的一部分时,为什么没有得到任何类型的错误。难道我不应该像一个
TypeError
那样告诉我对象
a
没有属性
hello
hello()
或者至少是这样的东西吗?这是怎么回事

我感谢您的解释,如果我错了,请纠正我的误解

多谢各位

for whatever in a():
  do_stuff_with_whatever(whatever)
如果
a()
返回一个包含元素的iterable,则只执行
do\u stuff\u with\u which
。否则,第一次通过时,
的值是多少

换句话说,语句
a.hello
a.hello()
永远没有机会执行,因为没有什么可重复的。如果将功能更改为:

def a():
    return [1]

然后您将开始看到一个
AttributeError
,因为
a
没有
hello
属性

多谢各位!这澄清了一切。