0
我在Python中學習OOP,並試圖在OOP風格中運行這個小遊戲,但由於某種原因系統找不到對象的屬性。猜數字,沒有這樣的屬性python 3
這裏的問題:
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()
由於'player_choice'和'compare_numbers'這兩個函數在*類中是*的,所以它們通過'self'對象在內部傳遞。因此,調用'self.player_choice()'應該可以工作 – jDo
您可能有興趣使用'classmethod'或'staticmethod',因爲對象不是真正需要的方法,您可以查看[this answer](http:// stackoverflow.com/questions/36076506/python3-nameerror-name-method-is-not-defined/36088022#36088022)有關它們如何工作的描述,但是jDo明白了:你需要調用'self.player_choice()'而不只是'player_choice()' –
這與Sublime Text有什麼關係?除非編輯器本身存在問題,否則請勿標記文本編輯器。 – MattDMo