从另一个函数调用一个函数内定义的variables

如果我有这个:

def oneFunction(lists): category=random.choice(list(lists.keys())) word=random.choice(lists[category]) def anotherFunction(): for letter in word: #problem is here print("_",end=" ") 

我以前定义了lists ,所以oneFunction(lists)完美地工作。

我的问题是在第6行调用word 。我试图用同样的word=random.choice(lists[category])定义来定义第一个函数外的word=random.choice(lists[category]) ,但是这使得word总是相同的,即使我调用oneFunction(lists)

我希望能够每次调用第一个函数,然后调用第二个函数时,都有不同的word

我可以这样做,而不是在oneFunction(lists)之外定义这个word吗?

是的,你应该考虑在一个类中定义你的function,并且把它作为一个成员。 这是更清洁

 class Spam: def oneFunction(self,lists): category=random.choice(list(lists.keys())) self.word=random.choice(lists[category]) def anotherFunction(self): for letter in self.word: print("_",end=" ") 

一旦你创build了一个类,你必须实例化它到一个对象并访问成员函数。

 s = Spam() s.oneFunction(lists) s.anotherFunction() 

另一种方法是使一个oneFunction返回单词,以便您可以在anotherFunction使用一个oneFunction而不是单词

 >>> def oneFunction(lists): category=random.choice(list(lists.keys())) return random.choice(lists[category]) >>> def anotherFunction(): for letter in oneFunction(lists): print("_",end=" ") 

最后,还可以创buildanotherFunction ,接受单词作为参数,您可以从调用oneFunction的结果中传递参数

 >>> def anotherFunction(words): for letter in words: print("_",end=" ") >>> anotherFunction(oneFunction(lists)) 

python中的所有东西都被认为是对象,所以函数也是对象。 所以你也可以使用这个方法。

 def fun1(): fun1.var = 100 print(fun1.var) def fun2(): print(fun1.var) fun1() fun2() print(fun1.var) 
 def anotherFunction(word): for letter in word: print("_", end=" ") def oneFunction(lists): category = random.choice(list(lists.keys())) word = random.choice(lists[category]) return anotherFunction(word) 

最简单的select是使用全局variables。 然后创build一个获取当前单词的函数。

 current_word = '' def oneFunction(lists): global current_word word=random.choice(lists[category]) current_word = word def anotherFunction(): for letter in get_word(): print("_",end=" ") def get_word(): return current_word 

这样做的好处是,也许你的function是在不同的模块,并需要访问variables。