2

我正在做一个猜数字游戏,我有一个“while True”循环,我想一直循环,直到用户猜对了数字。现在我显示了数字以便于测试。不管我猜对与否,我都会收到错误消息“'Nonetype' 对象没有属性'Guess'。” 我很困惑为什么“while True”第一次循环时没有错误,但之后又出现错误。

跟踪器.py

from Number import *

class Runner(object):
def __init__(self, start):
    self.start = start
    print Integer.__doc__
    print Integer.code

def play(self):
    next_guess = self.start

    while True:
        next_guess = next_guess.Guess()

        if next_guess == Integer.code:
            print "Good!"
            exit(0)

        else:
            print "Try again!"

Integer = Random_Integer()

Game = Runner(Integer)

Game.play()

数字.py

from random import randint

class Random_Integer(object):

"""Welcome to the guessing game! You have unlimited attempts
to guess the 3 random numbers, thats pretty much it."""

def __init__(self):
    self.code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    self.prompt = '> '

def Guess(self):
    guess_code = raw_input(self.prompt)

谢谢!

4

1 回答 1

8

您的.Guess()方法不返回任何内容:

def Guess(self):
    guess_code = raw_input(self.prompt)

您需要在return此处添加一条语句:

def Guess(self):
    guess_code = raw_input(self.prompt)
    return guess_code

当一个函数没有明确的 return 语句时,它的返回值总是None. 因此,该行:

next_guess = next_guess.Guess()

设置next_guessNone

但是,即使.Guess() 确实返回了raw_input()结果,您现在也已替换next_guess为字符串结果,并且您通过循环的下一次迭代现在将失败,因为字符串对象没有.Guess()方法。

Integer在将其作为参数传递给您的Runner()实例并将其存储在那里之后,您还可以在任何地方引用全局值self.start。不要依赖全局变量,您已经拥有self.start

class Runner(object):
    def __init__(self, start):
        self.start = start
        print start.__doc__
        print start.code

    def play(self):        
        while True:
            next_guess = self.start.Guess()

            if next_guess == self.start.code:
                print "Good!"
                exit(0)

            else:
                print "Try again!"

在上面的代码中,我们省略了访问Integer全局,而是使用self.start. 该next_guess变量严格用于保存当前的猜测,我们使用它self.start.Guess()来代替。

于 2013-06-13T16:29:49.977 回答