在Python中迭代对象列表时的打印结果为None

时间:2019-05-08 14:11:24

标签: 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 %@(*^%$

但它正在打印此提示:

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

请帮助

1 个答案:

答案 0 :(得分:1)

# 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作为函数。