Python返回值仅显示对象中的一个值,而不是所有值 [英] Python return value prints only one value from the object instead of all the values

查看:193
本文介绍了Python返回值仅显示对象中的一个值,而不是所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个类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.

在您的情况下,您可以简单地return 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆