【问题标题】:In Python, how to set value for one __init__ variable based on another?在 Python 中,如何根据另一个 __init__ 变量设置值?
【发布时间】:2018-03-26 04:35:48
【问题描述】:
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))

这只是返回错误:Name 'random_word' is undefined

【问题讨论】:

  • 您可以让 init 调用一个函数,并传入您生成的 random_word。

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


【解决方案1】:

你设置了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. ^^^^^

【讨论】:

    【解决方案2】:

    随便用吧:

    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

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 2014-10-06
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多