首页 > 解决方案 > 尝试打印类的对象时出现名称错误

问题描述

我是 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)

标签: listclassobjectattributes

解决方案


第一个问题:

在你的类中使用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数据模型


推荐阅读