在Python中,如何基于另一个__init__变量设置值?

时间:2017-10-14 01:59:18

标签: python python-3.x variables scope initialization

def __init__(self):
    #self.data = []
    self.random_word = random.choice(open("EnglishDictionary.txt").readlines()).strip()
    self.length_notice = "The word you're guessing is {} letters long.".format(len(random_word))

这只会返回错误:名称' random_word'未定义

2 个答案:

答案 0 :(得分:0)

您设置了self.random_word,而不是random_word,因此您需要使用 self.random_word

self.length_notice = "The word you're guessing is {} letters long.".format(len(self.random_word))
                                                                   # Add self. ^^^^^

答案 1 :(得分:0)

使用它:

def __init__(self):
    #self.data = []
    with open("EnglishDictionary.txt") as f:
        msg = "The word you're guessing is {} letters long."
        self.random_word = random.choice(f).strip()
        self.length_notice = msg.format(len(self.random_word))

问问自己,self.random_word是否真的需要是一个实例属性,或者random_word只能是函数内的局部变量,如msg