我编写了以下程序来演示类对象列表。它将名称和分数作为三个对象的输入,然后将其存储到列表中,最后程序显示所有信息,即与对象关联的名称和分数。
class Info:
def __init__(self, name, score):
self.name = name
self.score = score
def display(self):
print(f"Name :- {self.name}, Score :- {self.score}")
game_info = []
for i in range(3):
n = input("Enter Your Name :- ")
s = int(input("Enter Your Score :- "))
game_info.append(Info(n, s))
print()
for i in range(3):
print(game_info[i].display())
print()
输出:-
Enter Your Name :- a
Enter Your Score :- 1
Enter Your Name :- b
Enter Your Score :- 2
Enter Your Name :- c
Enter Your Score :- 3
Name :- a, Score :- 1
None
Name :- b, Score :- 2
None
Name :- c, Score :- 3
None
每次我尝试打印值时,输出都显示 None。那么我应该怎么做才能将其从程序输出中删除呢?
请您参考如下方法:
display 函数不返回任何内容。所以它默认为 None。 所以,
print(f"Name :- {self.name}, Score :- {self.score}")
打印您的预期输出。但这提示 None。
print(game_info[i].display())
你可以改变display函数,
return f"Name :- {self.name}, Score :- {self.score}".
