list - 尝试打印类的对象时出现名称错误
问题描述
我是 python 新手,需要一些帮助。我的代码如下。我正在尝试从输入的用户详细信息列表中获取格式化表,但不断收到错误消息,指出“名称错误:名称“游戏”未定义”不确定我做错了什么来打印它,请帮忙。
class game():
def _init_(self,name,platform,genre,no_of_players,online_functionality):
self.name = name
self.platform = platform
self.genre = genre
self.no_of_players = no_of_players
self.online_functionality = online_functionality
def __repr__(self):
print()
print("%-15s%-15s%-15s%-15s%-15s" % ("name" , "platform" ," genre" ,"no_of_players","online_functionality"))
print("---------------------------------------------------------------------------------")
print("%-10s%-10s%-10s%-10s%-10s%" %(games.name,games.platform,games.genre,games.no_of_players,games.online_functionality))
print()
def __str__(self):
print()
print("%-15s%-15s%-15s%-15s%-15s" % ("name" , "platform" ," genre" ,"no_of_players","online_functionality"))
print("------------------------------------------------------------------------")
print("%-10s%-10s%-10s%-10s%-10s%" %(games.name,games.platform,games.genre,games.no_of_players,games.online_functionality))#formats and aligns columns
print()
def get_game_from_user():
gameList =[]
games = game()
games.name= input("Enter name of game: ")
games.platform= input("Enter Platform (e.g. XBox, PlayStation, PC etc: ")
games.genre = input("Genre (e.g. Sport, Shooter, Simulation etc.): ")
games.no_of_players= int(input("Enter number of players: "))
games.online_functionality= input("Enter if it has online functionality or not : ")
gameList.append(games)
print(gameList)
解决方案
第一个问题:
在你的类中使用self
来访问你的对象 not games
。改变这些:
games.name, games.platform , games.genre, ...
和其他类似的东西:
self.name, self.platform , self.genre, ...
第二个问题:
在您的代码中,您必须在其中而不是它们return
中想要什么:__str__
__repr__
print
def __repr__(self):
result = ""
result += "%-15s%-15s%-15s%-15s%-15s" % ("name" , "platform" ," genre" ,"no_of_players","online_functionality\n")
result += "---------------------------------------------------------------------------------\n"
result += "%-10s%-10s%-10s%-10s%-10s" %(self.name,self.platform,self.genre,self.no_of_players,self.online_functionality)
result += "\n"
return result
来源:python数据模型
推荐阅读
- css - 按钮周围奇怪的分界线,是什么造成的?
- maven - 在构建 Maven 项目时遇到问题
- javascript - 想让机器人只向特定的人发送消息
- ios - UICollectionViewCompositionalLayout 将自己的高度约束添加到它的单元格
- python - Chart JS 使用 1,2,3 作为我的第二个数据集的点的 y 值,而不是它们传入的标签
- swift - Swift allSatisfy 允许“输入”或换行
- javascript - 获取请求用户名 firebase [VUE]
- vba - 在访问 vba 中,如果我尝试手动步进代码,它会工作 2-3 行,然后执行其余的不步进
- node.js - TypeError: (depth0 || container.hooks.helperMissing).call 不是函数
- javascript - Next js:将钩子作为参数传递给另一个文件中存在的函数是否很好?