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

在Python中,如何基于另一个_init__变量设置一个值?,python,python-3.x,variables,scope,initialization,Python,Python 3.x,Variables,Scope,Initialization,这只是返回错误:名称“random\u word”未定义,您设置了self.random\u word,而不是random\u word,因此您需要使用self.random\u word: def __init__(self): #self.data = [] self.random_word = random.choice(open("EnglishDictionary.txt").readlines()).strip() self.length_notice = "

这只是返回错误:名称“random\u word”未定义,您设置了
self.random\u word
,而不是
random\u word
,因此您需要使用
self.random\u word

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))

您设置了
self.random\u word
,而不是
random\u word
,因此需要使用
self.random\u word

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))
只要使用它:

self.length_notice = "The word you're guessing is {} letters long.".format(len(self.random_word))
                                                                   # Add self. ^^^^^
不过,问问自己,如果
self.random\u word
真的需要作为实例属性,或者
random\u word
可以只是函数内部的局部变量,比如
msg

,就使用它吧:

self.length_notice = "The word you're guessing is {} letters long.".format(len(self.random_word))
                                                                   # Add self. ^^^^^
问问你自己,如果
self.random\u word
真的需要作为实例属性,或者
random\u word
可以只是函数内部的局部变量,比如
msg

你可以让init调用函数,并传入你生成的随机词。你可以让init调用函数,并传入你生成的随机单词。