我在python中学习OOP并试图以OOP风格运行这个小游戏,但由于某种原因,系统找不到对象的属性。
问题在于:
Traceback (most recent call last): File "HelloUsername.py", line 47, in <module> newGameGTN = GuessTheNumber() File "HelloUsername.py", line 6, in __init__ self.start_game() File "HelloUsername.py", line 32, in start_game player = player_choice() NameError: name 'player_choice' is not defined
在python 3中使用此代码:
from random import randint
class GuessTheNumber(object):
"""docstring for GuessTheNumber"""
def __init__(self):
self.start_game()
self.player_choice()
self.compare_numbers()
def player_choice(self):
choice = int(input("Choose your number: "))
if choice in range(101):
return(choice)
else:
print("Please enter a number 0-100")
player_choice()
def compare_numbers(self, computer, player):
if player == computer:
return(0)
elif player > computer:
return(1)
elif player < computer:
return(-1)
def start_game(self):
computer = randint(0, 100)
turn = 0
for turn in range(3):
player = player_choice()
x = compare_numbers(computer, player)
print(computer)
if x == -1:
print("too small")
elif x == 1:
print("too big")
elif x == 0:
print("you win")
break
turn += 1
print("game over")
newGameGTN = GuessTheNumber()
newGameGTN.start_game()
答案 0 :(得分:0)
NameError
与AttributeError
(您在问题摘要中提到的)不同。 NameError
异常表示代码中引用的名称不存在。名称可以是局部变量,也可以是封闭范围中的变量。
需要在该类的实例上调用类中的所有方法。 (静态方法和类方法不能承受)而不是name = player_choice()
你需要写name = self.player_choice()
。同样适用于调用类中定义的方法的所有其他事件。