Python 返回值仅打印对象中的一个值而不是所有值 [英] Python return value prints only one value from the object instead of all the values
问题描述
我有一个包含两个类 A 和 B 的 Python 文件,并且我从 A 类到 B 继承了 temp.在我的 A 类函数 temp 中,我从具有如下值的 XML 文件中获取 id 值,
I have a Python file with two class A and B, and I am inheriting temp from class A to B. In my class A function temp, I am getting the id value from an XML file which has values like this,
[1,2,3,4,5]
我的A类带临时功能
class A:
def temp(self):
id = []
for child in root:
temp_id=child.get('id')
id.append(temp_id)
return id
并且我正在获取 B 类中的函数值,
and I am getting the function value in class B,
class B (A):
fun=A
value = fun.temp()
for x in value:
return x
在打印返回值而不是打印所有值时,我只得到第一个值
While printing the return value instead of printing all the values, I am getting only the first value
[1,1,1,1,1]
谁能告诉我如何解决这个问题,谢谢.
Can some one please let me know on how to solve this, thanks.
推荐答案
标准函数只能返回一个值.之后,从调用该函数的位置继续执行.因此,您尝试遍历所有值,但在看到第一个值时返回,然后函数退出且循环中断.
Standard functions can only return a single value. After that, execution continues from where that function was called. So, you're trying to loop through all the values, but return upon seeing the first value, then the function exits and the loop is broken.
在您的情况下,您可以简单地返回 fun.temp()
.或者,如果你想处理每个值,然后返回新列表,你可以运行如下:
In your case, you could simply return fun.temp()
. Or, if you want to process each value, then return the new list, you could run something like:
new_list = []
value = fun.temp()
for x in value:
# do something with x here
new_list.append(x)
return new_list
此外,您似乎对继承的工作方式有些困惑.DigitalOcean 有一篇关于它的好文章,如果你想看看.
Also, it appears you may be a bit confused about how inheritance works. DigitalOcean has a great article on it, if you want to take a look.
这篇关于Python 返回值仅打印对象中的一个值而不是所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!