对返回对象进行迭代 [英] Iterating on return object
问题描述
定义的对象中的迭代值,但是当我调用函数 process_test()
,循环停止,因为我返回的对象。
如何让函数 process_test()
创建对象并赋值 i
在每个循环上?
class test(object):
abc = 0
cde = 0
def process_test():
我在xrange(5)中:
#print i
myobj = test()
myobj.abc =
#print myobj.abc
返回myobj.abc
$ b myobj = process_test()
打印myobj
输出:
0
所需输出:
0
1
2
3
4
5
解决方案当您第一次从函数中返回时,您不再处于该函数中。你需要将值存储在一个列表中,然后返回它
$ b $ pre code class test(object)
abc = 0
$ c $ =
def process_test():
L = []
我在xrange(6)中:
#print i
myobj = test()
myobj.abc = i
#print myobj.abc
L.append(myobj.abc)
return L
myobj = process_test()
for myobj:
print x
<希望,这将有助于。
I am trying OOP with Python. I need to get the iterating values in objects as defined by the for
loop, but as I call my function process_test()
, the loop stops as I return the object.
How can I make the function process_test()
create objects and assign values of i
on it on each loop?
class test(object):
abc = 0
cde = 0
def process_test():
for i in xrange(5):
# print i
myobj = test()
myobj.abc = i
#print myobj.abc
return myobj.abc
myobj = process_test()
print myobj
Output:
0
Desired Output:
0
1
2
3
4
5
When you first return from the function, you are no longer in that function. You need to store value in a list, then return it
class test(object):
abc = 0
cde = 0
def process_test():
L = []
for i in xrange(6):
# print i
myobj = test()
myobj.abc = i
#print myobj.abc
L.append(myobj.abc)
return L
myobj = process_test()
for x in myobj:
print x
Hope, it will help.
这篇关于对返回对象进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!