无法遍历 class 的实例列表
Can't iterate through a list of istances of a class
我构建了一个列表,其中包含我创建的自定义实例 class。现在我可以像这样访问单个属性:
Name_of_list[Index of specific object].attribute1
但是:如果我想遍历 bbjects,我无法访问属性,出现以下消息:
"TypeError: 'int' object is not iterable".
print(list)
[<__main__.Costumer object at 0x00000000118AA3C8>,
<__main__.Costumer object at 0x000000000E3A69E8>,
<__main__.Costumer object at 0x000000000E3A6E10>]
你的错误在循环初始化行
for k in 3:
您不能使用 in
关键字进行迭代,您需要迭代可以使用 range
生成的序列
>>>for k in range(3):
... print(k)
0
1
2
编辑
我看到我得到了一些反对票,所以我想我会尝试澄清一些事情。
首先,OPs 的问题是他在一行代码上遇到错误,此后 OPs 代码已在编辑中删除。
代码在这条路径上发生了一些事情
class MyClass:
def attribute(self):
pass
instances = [MyClass(), MyClass(), MyClass()]
for k in 3:
instances[k].attribute()
他收到了这个错误 TypeError: 'int' object is not iterable
。
为此,我回答(并且 OP 接受了)错误是要使用 for
和 in
你需要一个序列。
事实上,使用
更符合 pythonic(也更易读)
for ins in instances:
ins.attribute()
或者如果需要跟踪当前实例的索引以使用 enumerate
当与可迭代对象一起使用时 returns 索引和当前对象的元组
for k, ins in enumerate(instances):
# k will be the current index, and ins will be the current instance.
Python 让你遍历 iterator object. You don't need to use range
and indexes for this, Python does it for you under the hood, as can be seen :
for customer in list:
print(customer.attribute1)
文档中的迭代器定义:
An object representing a stream of data. Repeated calls to the iterator’s next() method (or passing it to the built-in function next()) return successive items in the stream.
我构建了一个列表,其中包含我创建的自定义实例 class。现在我可以像这样访问单个属性:
Name_of_list[Index of specific object].attribute1
但是:如果我想遍历 bbjects,我无法访问属性,出现以下消息:
"TypeError: 'int' object is not iterable".
print(list)
[<__main__.Costumer object at 0x00000000118AA3C8>,
<__main__.Costumer object at 0x000000000E3A69E8>,
<__main__.Costumer object at 0x000000000E3A6E10>]
你的错误在循环初始化行
for k in 3:
您不能使用 in
关键字进行迭代,您需要迭代可以使用 range
>>>for k in range(3):
... print(k)
0
1
2
编辑
我看到我得到了一些反对票,所以我想我会尝试澄清一些事情。
首先,OPs 的问题是他在一行代码上遇到错误,此后 OPs 代码已在编辑中删除。
代码在这条路径上发生了一些事情
class MyClass:
def attribute(self):
pass
instances = [MyClass(), MyClass(), MyClass()]
for k in 3:
instances[k].attribute()
他收到了这个错误 TypeError: 'int' object is not iterable
。
为此,我回答(并且 OP 接受了)错误是要使用 for
和 in
你需要一个序列。
事实上,使用
for ins in instances:
ins.attribute()
或者如果需要跟踪当前实例的索引以使用 enumerate
当与可迭代对象一起使用时 returns 索引和当前对象的元组
for k, ins in enumerate(instances):
# k will be the current index, and ins will be the current instance.
Python 让你遍历 iterator object. You don't need to use range
and indexes for this, Python does it for you under the hood, as can be seen
for customer in list:
print(customer.attribute1)
文档中的迭代器定义:
An object representing a stream of data. Repeated calls to the iterator’s next() method (or passing it to the built-in function next()) return successive items in the stream.