【问题标题】:NameError: name 'self' is not defined at the last block only?NameError:名称'self'仅在最后一个块中没有定义?
【发布时间】:2017-08-07 12:49:35
【问题描述】:

为什么在我运行此代码时它告诉我“NameError: name 'self' is not defined”? 我不知道为什么一切都很好,除了最后一个块(更新方法)给了我任何人都可以提供帮助的错误?

此代码是一个游戏,它采用手的长度并给你一个随机字母来从手上创建一个单词,当你输入一个正确的单词时,单词中使用的字母会自动删除,直到单词

import random 

class Hand(object):

    self.hand = {}

    def __init__(self, n):
        '''
        Initialize a Hand.

        n: integer, the size of the hand.
        '''
        assert type(n) == int
        self.HAND_SIZE = n
        self.VOWELS = 'aeiou'
        self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'

        # Deal a new hand
        self.dealNewHand()

    def dealNewHand(self):
        '''
        Deals a new hand, and sets the hand attribute to the new hand.
        '''
        # Set self.hand to a new, empty dictionary
        self.hand = {}

        # Build the hand
        numVowels = self.HAND_SIZE // 3

        for i in range(numVowels):
            x = self.VOWELS[random.randrange(0,len(self.VOWELS))]
            self.hand[x] = self.hand.get(x, 0) + 1

        for i in range(numVowels, self.HAND_SIZE):    
            x = self.CONSONANTS[random.randrange(0,len(self.CONSONANTS))]
            self.hand[x] = self.hand.get(x, 0) + 1

    def setDummyHand(self, handString):
        '''
        Allows you to set a dummy hand. Useful for testing your implementation.

        handString: A string of letters you wish to be in the hand. Length of this
        string must be equal to self.HAND_SIZE.

        This method converts sets the hand attribute to a dictionary
        containing the letters of handString.
        '''
        assert len(handString) == self.HAND_SIZE, "Length of handString ({0}) must equal length of HAND_SIZE ({1})".format(len(handString), self.HAND_SIZE)
        self.hand = {}
        for char in handString:
            self.hand[char] = self.hand.get(char, 0) + 1


    def calculateLen(self):
        '''
        Calculate the length of the hand.
        '''
        ans = 0
        for k in self.hand:
            ans += self.hand[k]
        return ans

    def __str__(self):
        '''
        Display a string representation of the hand.
        '''
        output = ''
        hand_keys = sorted(self.hand.keys())
        for letter in hand_keys:
            for j in range(self.hand[letter]):
                output += letter
        return output

    def update(self, word):
        """
        Does not assume that self.hand has all the letters in word.

        Updates the hand: if self.hand does have all the letters to make
        the word, modifies self.hand by using up the letters in the given word.

        Returns True if the word was able to be made with the letter in
        the hand; False otherwise.

        word: string
        returns: Boolean (if the word was or was not made)
        """

        for i in word :
            if self.hand.get(i , 0) == 0 :
                return False
            else :
                self.hand[i] -=1
        return True

【问题讨论】:

  • 我认为这是问题所在:self.hand = {} 在您班级的顶部。在定义类时没有self。此行应该在您的 __init__ 方法内。
  • 您在课堂正文中有self.hand = {}
  • self 不是一个 Python 关键字,就像 JS 中几乎等效的 this 一样。这是一种传统用法。

标签: python python-3.x random


【解决方案1】:

我认为是这一行:

self.hand = {}

在你班级的顶部,这就是问题所在。在定义类时没有self。此行应您的__init__ 方法中。

def __init__(self, n):
    '''
    Initialize a Hand.

    n: integer, the size of the hand.
    '''
    self.hand = {}
    # ... and the rest

【讨论】:

  • 谢谢,它运行良好,但你能告诉我为什么当我删除方法“update”时它运行良好,而无需在我的 init 方法中定义这一行 *注意它已被使用在其他一些方法中没有给出错误
  • 如果你的类顶部的self.hand = {}能够成功执行,无论update方法是否被定义,我都会感到惊讶。
猜你喜欢
  • 1970-01-01
  • 2021-10-23
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2020-01-17
  • 1970-01-01
相关资源
最近更新 更多