Python类不起作用

时间:2014-06-16 00:49:56

标签: python class

当我运行此代码时,它确实转到_init_函数,我不知道为什么。我最后用hangman = Main()称呼它,但它无效。

class Main:

    wordToGuess = 'world cup'
    displayWord = '***** ***'
    num_wrong = 0;    

    def _init_(self):
        print('lets play!')
        while True:
            letter = input('Enter guess: ')
            isDansWord = self.isInWord(letter)
            if isDansWord:
                self.updateDisplayWord(letter)
                print(self.displayWord)
                if self.checkForWin():
                    self.win()
                    break
                else:
                    print('wrong')
                    self.num_wrong += 1
                    if self.checkForLoss():
                        self.loss()
                        break

    def isInWord(self,letter):
        inWord = False
        for x in range(0, len(self.displayWord)):
            if self.wordToGuess[x:x + 1] == letter:
                inWord = True
                break
        return inWord

    def checkForWin(self):
        if self.wordToGuess == self.displayWord:
            return True
        else:
            return False

    def checkForLoss(self):
        if self.num_wrong > 5:
            return True
        else:
            return False

    def win(self):
        print('you win!')

    def loss(self):
        print('you lose!')

print('Hangman\n')

hangman = Main()

3 个答案:

答案 0 :(得分:3)

您需要4个下划线:

__init__,而非_init_

答案 1 :(得分:2)

__init__方法是Python中的special method。特殊方法以双下划线__开头和结尾,因此您的方法应该是:

def __init__(self):

答案 2 :(得分:1)

请不要_init_,而是__init__(两个" _"来自每一方)。