2017-10-14 13 views
1
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)) 

Ce que renvoie l'erreur: Nom 'random_word' est pas définiEn Python, comment définir une valeur pour une variable __init__ basée sur une autre?

+0

Vous pouvez avoir __init__ appeler une fonction et transmettre le mot aléatoire que vous avez généré. – Raizuri

Répondre

0

Vous définissez self.random_word, pas random_word, vous devez utiliserself.random_word:

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

Hey merci! Je me sens stupide –

0

utiliser Il suffit de:

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

Demandez-vous, cependant, si self.random_word doit vraiment être un attribut d'instance, ou si random_word peut simplement être une variable locale dans la fonction, comme msg.