简体   繁体   English

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

[英]In Python, how to set value for one __init__ variable based on another?

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

This just returns the error: Name 'random_word' is undefined 这只会返回错误:名称'random_word'未定义

You set self.random_word , not random_word , so you need to use self.random_word : 您设置的是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. ^^^^^

Just use it: 只需使用它:

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

Ask yourself, though, if self.random_word really needs to be an instance attribute, or if random_word can simply be a local variable inside the function, like msg . 但是,请问问自己, self.random_word确实需要作为实例属性,或者random_word可以简单地作为函数内部的局部变量,例如msg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM