python - 在 Python 中迭代对象列表时打印 None

标签 python python-3.x

我试图遍历一个对象列表,但我一直在每行后面打印一个“无”

class UserInfo():
    def __init__(self, name = str(), key = str(), ID = str()):
        self.name = name
        self.key = key
        self.ID = ID
    def info(self):
        print ("the user name is {}, the ID is {} and the key is {}".format(self.name, self.ID, self.key))

user1 = UserInfo( name = 'Mike Mourise',key = '%#^*^%#', ID = 'SVAR231G')
user2 = UserInfo( name = 'Alex Kurt',key = '%#^*^!@', ID = 'SW1I2X45')
user3 = UserInfo( name = 'Kevin Heart',key = '%@(*^%$', ID = 'BOET34617') 
users = [user1, user2, user3]

for person in users:
    print (person.info())

我想让它打印这个:

the user name is Mike Mourise, the ID is SVAR231G and the key is %#^*^%#
the user name is Alex Kurt, the ID is SW1I2X45 and the key is %#^*^!@
the user name is Kevin Heart, the ID is BOET34617 and the key is %@(*^%$

但它正在打印这个 isstead:

the user name is Mike Mourise, the ID is SVAR231G and the key is %#^*^%#
None
the user name is Alex Kurt, the ID is SW1I2X45 and the key is %#^*^!@
None
the user name is Kevin Heart, the ID is BOET34617 and the key is %@(*^%$
None

请帮忙

最佳答案

# your code goes here
class UserInfo():
    def __init__(self, name , key, ID ):
        self.name = name
        self.key = key
        self.ID = ID
    def info(self):
        #use return
        return ("the user name is {}, the ID is {} and the key is {}".format(self.name, self.ID, self.key))

user1 = UserInfo( name = 'Mike Mourise',key = '%#^*^%#', ID = 'SVAR231G')
user2 = UserInfo( name = 'Alex Kurt',key = '%#^*^!@', ID = 'SW1I2X45')
user3 = UserInfo( name = 'Kevin Heart',key = '%@(*^%$', ID = 'BOET34617') 
users = [user1, user2, user3]

for person in users:
    print (person.info())

它打印 None 的原因是因为您从未返回任何东西。不使用 print,而是使用 return 作为函数。

关于python - 在 Python 中迭代对象列表时打印 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56042787/

相关文章:

python - multiprocessing.Pool() 比仅使用普通函数慢

python - 在另一个列表中查找一个列表的值的索引

python-3.x - Python 字节表示

python - 有没有办法将24小时时间格式转换为一天的四个类别或四个象限?

python - 为什么排序列表比未排序列表大

python - 导入错误 : No module named cv2. 简历

python - 如何用python将字符串拆分为2?

python - 我如何使用 PyTorch 0.4.0 从 numpy 数组制作一个带有 requires_grad=True 的 FloatTensor?

python - 使用 pyinstaller 找不到 .exe 文件的输出文件夹

python - 如何对过滤器进行单元测试?