未调用的对象的属性错误[关闭]
Posted
技术标签:
【中文标题】未调用的对象的属性错误[关闭]【英文标题】:Attribute error from an object that isn't called upon [closed] 【发布时间】:2021-12-27 06:23:19 【问题描述】:我正在使用 python 开发 Mastermind 游戏,我的一个课程称为 Game 课程。这会运行游戏的“设置”(例如查找玩家人数、玩家姓名等)。但是,当我尝试将名称附加到在我的 Game 类中创建的新列表中时,我检查输入的名称与先前定义/存储在单独类中的玩家列表的方法之一是引发 AttributeError。这是我的 Game 类目前的样子:
class WorldOfMastermind:
"""WOM class - Runs whole game, takes results from other classes and stores them (namely players and their scores)"""
def __init__(self):
self.__playerList = []
self.__playerDetails = dict()
def run(self):
"""Run method - holds the menu screen - allows for the user to add player, show scores, play game or quit"""
cpuNames = ComputerPlayer.addDetails(self)
self.__playerList.extend((cpuNames))
start = input('What would you like to do?\n (r) register a new user\n (s) show the score board\n (p) play a game\n (q) quit\n')
if start == 'r':
tempName = HumanPlayer.addDetails(self)
for i in self.__playerList:
if i == tempName:
print('')
print('Sorry, that name already exists')
print('')
self.run()
self.__playerList.append(tempName)
self.__playerDetails[tempName] = [0, 0, float(0)]
print('Welcome,', tempName + '!')
print('')
self.run()
elif start == 's':
self.printScoreBoard()
elif start == 'p':
print('Let\'s play the game of Mastermind!')
Game.startPrep(self, self.__playerList)
elif start == 'q':
print('Thank you for playing the World of Mastermind!')
exit()
else:
print('\nSorry, that is an invalid input')
print('')
self.run()
def printScoreBoard(self):
""" Print the scoreboard by iterating through the dictionary """
print('=====================================')
print('Name Score Games Average ')
print('=====================================')
for i in self.__playerDetails:
print(':<15 '.format(i), ':>5'.format(self.__playerDetails[i][0]), ':>5'.format(self.__playerDetails[i][1]), ':>7'.format(self.__playerDetails[i][2]))
print('=====================================\n')
self.run()
class Game:
"""Begin the initialization of the game and return results to WOM class"""
def __init__(self, playerCount):
self.__playerCount = playerCount
self.__playingList = []
def startPrep(self, playerList):
"""Prepares the game"""
Game.getPlayerCount(self)
Game.getPlayerNames(self, playerList)
def getPlayerCount(self):
"""Gathers the number of players"""
while True:
try:
self.__playerCount = int(input('How many players (2-4)?'))
except ValueError:
print('Only numbers allowed')
else:
if self.__playerCount < 2 or self.__playerCount > 4:
print('Player count must be between 2-4 inclusive')
else:
break
def getPlayerNames(self, playerList):
"""Gathers names of players and puts them into a list"""
while True:
if self.__playerCount == 2:
while True:
player1 = input('What is the name of player #1?')
if player1 in playerList:
print('successful')
self.__playingList.append(player1)
break
else:
print('Invalid username')
while True:
player2 = input('What is the name of player #2?')
if player2 in playerList:
if player2 not in self.__playingList:
print('successful')
self.__playingList.append(player2)
break
else:
print(player2, 'is already in the game.')
else:
print('Invalid username')
break
我觉得错误来自于调用 getPlayerNames 方法。由于它需要一个参数(来自另一个类的玩家列表),这纯粹是为了检查输入的名称是否真的在游戏中,如果是这样,它会打印“成功”(它确实如此)但是在尝试附加输入的名称时进入新的“playingList”会引发错误。我不确定为什么会这样,因为附加行不需要引用另一个类的属性。任何建议将不胜感激!
【问题讨论】:
发布错误的完整回溯。 这正是您的文件的外观吗?因为“类”行之后的所有内容都应该缩进一个位置。一旦我这样做了,您的代码就会为我正确运行。我确实想知道,当您立即忽略这两个值并从终端读取时,为什么要将玩家数量传递给__init__
并将玩家列表传递给 getPlayerName
。
@TimRoberts 我不知道为什么,但几乎每个人在粘贴代码时都会遇到问题,而且第一行永远不会正确缩进。我只是定期修复它。
不要写Game.getPlayerCount(self)
。写self.getPlayerCount()
。与下一行相同。
self.__playingList.append(player1) AttributeError: 'WorldOfMastermind' object has no attribute '_Game__playingList' 我不想把我所有的代码都放进去,因为我不想让它看起来太混乱,但如果你愿意,我可以添加 WorldOfMastermind 课程
【参考方案1】:
您的代码适用于我,格式如下。如果我运行以下代码,它会询问玩家人数并确保您提供的名称在符合条件的玩家列表中。
class Game:
"""Begin the initialization of the game and return results to WOM class"""
def __init__(self, playerCount=0):
self.__playerCount = playerCount
self.__playingList = []
def startPrep(self, eligible):
"""Prepares the game"""
self.getPlayerCount()
self.getPlayerNames(eligible)
def getPlayerCount(self):
"""Gathers the number of players"""
while True:
try:
self.__playerCount = int(input('How many players (2-4)?'))
except ValueError:
print('Only numbers allowed')
else:
if self.__playerCount < 2 or self.__playerCount > 4:
print('Player count must be between 2-4 inclusive')
else:
break
def getPlayerNames(self, playerList):
"""Gathers names of players and puts them into a list"""
for i in range(self.__playerCount):
while True:
s = 'What is the name of player #%d? '%(i+1)
player = input(s)
if player in playerList:
print('successful')
self.__playingList.append(player)
break
else:
print('Invalid username')
g = Game()
g.startPrep(['bob','bill'])
【讨论】:
好吧,我明白了,我只是没有创建一个调用该类的变量,而是尝试直接从另一个类调用该函数。这现在对我有用。谢谢以上是关于未调用的对象的属性错误[关闭]的主要内容,如果未能解决你的问题,请参考以下文章
Asp.net MVC 中的 jquery 验证错误 - 无法获取属性“调用”的值:对象为空或未定义
如何修复 React 中的“类型错误:尝试访问对象的属性时无法读取未定义的属性名称”
未捕获的类型错误:无法读取未定义的属性“ContentContainer”[关闭]