gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:00:24 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com